简体   繁体   English

使用Moq模拟一个类而不是整个类的一个方法?

[英]Mock one method on a class instead of the whole class using Moq?

I have a class 我上课了

public interface IMyInterface 
{
    string MethodA();
    void MethodB();
}

public class MyClass : IMyInterface
{
    public string MethodA()
    {
        // Do something important
    }

    public void MethodB()
    {
        string value = MethodA();
        // Do something important
    }
}

I want to unit test MethodB, but I'm having trouble thinking about how I can Mock MethodA while still calling into MethodB using Moq. 我想对单元测试方法B进行单元测试,但是我在考虑如何使用Moq调用MethodB时无法模拟MethodA Moq mocks the interface, not the class, so I can't just call mock.Object.MethodB() , right? Moq模拟了接口,而不是类,所以我不能只调用mock.Object.MethodB() ,对吗?

Is this possible? 这可能吗? If so, how? 如果是这样,怎么样?

I don't think it is possible. 我不认为这是可能的。 Even it is possible I'd prefer not to do that. 即使有可能我也不愿意这样做。

You are testing behavior of MyClass , the fact that it happen to implement IMyInterface is somewhat unrelated to testing behavior of MethodA and MethodB. 您正在测试的行为MyClass ,它发生在执行的事实IMyInterface是有些无关的治法和方法b的测试行为。 You can have separate test that makes sure that class implements interfaces that you expect it to implement if necessary. 您可以进行单独的测试,以确保该类实现您希望在必要时实现的接口。 Testing of MyClass.MethodB should be done on instance of MyClass, not on semi-mocked object. MyClass.MethodB的测试应该在MyClass的实例上完成,而不是在半模拟对象上。

If you think that behavior of MethodA is dependency you may try actually extract it explicitly from the class. 如果您认为MethodA的行为是依赖性,您可以尝试从类中明确地提取它。 It will allow to test both MethodA (which will simply delegate to the dependency) and MethodB (which will use the dependency and do more). 它将允许测试MethodA(它将简单地委托给依赖项)和MethodB(它将使用依赖项并做更多)。

Mock dependencies you cannot instanciate easily (or all). 模拟依赖关系,你不能容易(或所有)实例化。
MyClass is class under test, so should not be mocked (you don't want to test mocked values). MyClass是测试中的类,所以不应该被模拟(你不想测试模拟的值)。
But, if you have some MyClass.Foo property that is class Foo which implements IFoo interface and MethodA uses this Foo property, then you can mock it to break dependency. 但是,如果你有一些MyClass.Foo属性是类Foo ,它实现了IFoo接口而MethodA使用了这个Foo属性,那么你可以模拟它来破坏依赖。

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

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