Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 单元测试从抽象类继承的类_C#_Unit Testing_Moq_Abstract Class - Fatal编程技术网

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

C# 单元测试从抽象类继承的类,c#,unit-testing,moq,abstract-class,C#,Unit Testing,Moq,Abstract Class,我的问题是,我想在抽象类中存根一个属性,因为测试中的类使用该属性。我目前正在使用最新版本的Moq 我的抽象类如下所示: public abstract class BaseService { protected IDrawingSystemUow Uow { get; set; } } public class UserService : BaseService, IUserService { public bool UserExists(Model model) {

我的问题是,我想在抽象类中存根一个属性,因为测试中的类使用该属性。我目前正在使用最新版本的Moq

我的抽象类如下所示:

public abstract class BaseService
{
    protected IDrawingSystemUow Uow { get; set; }
}
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;
    }
}
我的测试课是这样的:

public abstract class BaseService
{
    protected IDrawingSystemUow Uow { get; set; }
}
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;
    }
}

我不知道如何存根
Uow
属性。有人有什么线索吗?或者我的设计太糟糕了,以至于我需要在测试中将
Uow
属性移动到我的类中?

您当前的设置无法工作,原因很简单-
Uow
属性是不可重写的,Moq的工作此时完成

最简单的解决方案是简单地使该属性可重写。将基类定义更改为:

public abstract class BaseService
{
    protected virtual IDrawingSystemUow Uow { get; set; }
}
现在您可以使用Moq的受保护特性(这要求您在测试类中包括
使用Moq.protected
命名空间):

//在文件的顶部
使用最小起重量保护;
// ...
var drawingsystemtub=new Mock();
var testedClass=new Mock();
测试类
.Protected()
.设置(“Uow”)
.Returns(drawingSystemStub.Object);
//将drawingSystemStub设置为任何其他存根
//运动试验
var result=testedClass.Object.UserExists(…);

我认为你的情况很简单。您只是不模拟
Uow
属性,而是模拟
idrawingsystemow
服务。因此,您可以创建
idrawingsystemow
的模拟,通过
Uow
属性将其分配给
UserService
的实例,然后运行测试(例如
UserExists
方法)。

非常感谢您的帮助!这是代码片段中的一个小错误。返回(drawingSystemStub)应替换为返回(drawingSystemStub.Object)。=)仅供参考@jimmy_keen-无法覆盖、无法模拟的链接已断开