简体   繁体   English

如何使用Moq具有使用模拟对象的方法操作的能力?

[英]How to use Moq to have an ability to use method operation of mocked object?

I have an instantiation in constructor in test: 我在测试中的构造函数中有一个实例化:

public class Car{

public string Method()
{
 return "test";
}
}

private readonly ICar _classUnderTest;
    public CarTests()
    {
        var collaboratingClass = new CollaboratingClass();
        _classUnderTest = new Car(collaboratingClass );
    }

If I use moq and pass mock instance like this: 如果我使用moq并像这样传递模拟实例:

    var collaboratingClass = new Mock<ICollaboratingClass>();
    _classUnderTest = new Car(collaboratingClass .Object);

...then I can't call method. ...然后我无法调用方法。 The method from this mocked instance is not being called, so I can't use it for calculation. 该模拟实例中的方法没有被调用,因此我无法将其用于计算。 How can I make my mock object to be able to access method and do operation with mock object? 如何使我的模拟对象能够访问方法并使用模拟对象进行操作?

As you can see I don't want to have concrete dependencies here. 如您所见,我不想在这里有具体的依赖关系。

You can fake a return to your mocked class method. 您可以伪造返回到模拟类方法的内容。 If you need the behavior from your dependency, it's no longer a unit test 如果您需要依赖项中的行为,则不再是单元测试

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

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