如何模拟泛型抽象类 [英] How to mock a Generic Abstract class

查看:107
本文介绍了如何模拟泛型抽象类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个接口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);

,但请注意,所有属性必须为virtualabstract.

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 { } }
}

这篇关于如何模拟泛型抽象类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆