How to mock a Generic Abstract class

☆樱花仙子☆ 提交于 2019-12-13 13:32:51

问题


Assuming I have an Interface IReportBuilderService and concrete class ReportBuilderService

e.g. public class ReportBuilderService : IReportBuilderService { }

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()

where a TReport is defined as

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

And Report class is simply

public class Report { }

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

Hope this makes sense


回答1:


Given that your abstract class looks like this:

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

there's no problem in mocking it at all:

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

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

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


来源:https://stackoverflow.com/questions/15143629/how-to-mock-a-generic-abstract-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!