如何模拟泛型抽象类

编程入门 行业动态 更新时间:2024-10-27 06:21:59
本文介绍了如何模拟泛型抽象类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

假设我有一个接口IReportBuilderService和具体的类ReportBuilderService

Assuming I have an Interface IReportBuilderService and concrete class ReportBuilderService

e.g. public class ReportBuilderService : IReportBuilderService { }

我可以像这样用Moq来模拟这项服务

I can start to mock this service with Moq as such

Mock<IReportBuilderService> _reportBuilderServiceMock = new Mock<IReportBuilderService>();

还有模拟类上的模拟期望,好吧,没问题.

And mock expectations etc on the mock class, ok no problems.

问题:如何模拟以下方法签名?

Question: How do I mock the following method signature?

public abstract class ReportBuilder<TReport> where TReport : Report, new()

其中TReport被定义为

where a TReport is defined as

public class SomeReport : ReportBuilder<Report>, IMapper{}

Report类很简单

And Report class is simply

public class Report { }

在抽象类ReportBuilder中,有一系列的属性获取/设置,这就是我要伪造/模拟的属性的值.

In the abstract class ReportBuilder there are a series of Property Get/ Sets, it is the value of these that I’m trying to fake/mock.

但是我不能从这个抽象类开始以正确的模拟开始

But I can’t begin to get the correct mock on this abstract class to start with

希望这很有意义

推荐答案

鉴于您的抽象类如下所示:

Given that your abstract class looks like this:

public abstract class ReportBuilder<TReport> where TReport : Report, new() { public abstract Int32 SomeThing { get; set; } }

完全没有问题可言:

var m = new Mock<ReportBuilder<Report>>(); m.SetupProperty(r => r.SomeThing, 19);

,但请注意,所有属性必须为virtual或abstract.

but note that all your properties have to be virtual or abstract.

因此,如果不是这种情况(并且您不能或不想更改它),则可以从基类中提取一个interface并使用它(如果您愿意更改您的相应的代码),或者只是通过子类化来创建存根/模拟:

So if this is not the case (and you can't or don't want to change this), you could either extract an interface from your base class and use this (if you're willing to change your code accordingly), or simply create a stub/mock by subclassing:

public class StubReportBuilder : ReportBuilder<Report> { public override Int32 SomeThing { get { return 42; } set { } } }

更多推荐

如何模拟泛型抽象类

本文发布于:2023-10-31 05:42:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1545178.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:抽象类

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!