假设我有一个接口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 { } } }更多推荐
如何模拟泛型抽象类
发布评论