简体   繁体   English

单元测试从抽象类继承的类

[英]Unit testing a class that inherits from an abstract class

My problem is that I want to stub a property in my abstract class, because my class in test uses that property. 我的问题是我想在我的抽象类中存根一个属性,因为我在测试中的类使用了该属性。 I'm currently using latest version of Moq. 我目前正在使用最新版本的Moq。

My abstract class looks like this: 我的抽象类看起来像这样:

public abstract class BaseService
{
    protected IDrawingSystemUow Uow { get; set; }
}

And my class in test looks like this: 我的测试课看起来像这样:

public class UserService : BaseService, IUserService
{
    public bool UserExists(Model model)
    {
        var user = this.Uow.Users.Find(model.Id);
        if(user == null) { return false; }

        reurn true;
    }
}

I can't figure out how I can stub the Uow property. 我无法弄清楚如何存根Uow属性。 Does anybody have any clue? 有人有任何线索吗? Or is my design that bad that I need to move to Uow property to my class in test? 或者我的设计是不是很糟糕,我需要在测试Uow属性转移到我的班级?

Your current setup won't work for one simple reason - Uow property is non-overridable and Moq's job is done at this point. 您当前的设置不会出于一个简单的原因 - Uow属性是不可Uow ,Moq的工作就在此时完成。 Cannot override, cannot mock . 无法覆盖,无法模拟

Easiest solution is to simply make that property overridable. 最简单的解决方案是简单地使该属性可以覆盖。 Change your base class definition to: 将基类定义更改为:

public abstract class BaseService
{
    protected virtual IDrawingSystemUow Uow { get; set; }
}

Now you can use Moq's protected feature (this requires you to include using Moq.Protected namespace in your test class): 现在您可以使用Moq的受保护功能(这要求您在测试类中using Moq.Protected命名空间):

// at the top of the file
using Moq.Protected;

// ...

var drawingSystemStub = new Mock<IDrawingSystemUow>();
var testedClass = new Mock<UserService>();
testedClass 
  .Protected()
  .Setup<IDrawingSystemUow>("Uow")
  .Returns(drawingSystemStub.Object);

// setup drawingSystemStub as any other stub

// exercise test
var result = testedClass.Object.UserExists(...);

I think in your case it's pretty straightforward. 我认为在你的情况下它非常简单。 You just don't mock the Uow property but the IDrawingSystemUow service. 你只是不模仿Uow属性,而是IDrawingSystemUow服务。 So you can create a mock of IDrawingSystemUow , assign it to the instance of UserService via the Uow property and then run the tests (eg of the UserExists method). 因此,您可以创建IDrawingSystemUow的模拟,通过Uow属性将其分配给UserService的实例,然后运行测试(例如UserExists方法)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM