Moq fake one method but use real implementation of another

前端 未结 2 1118
北荒
北荒 2021-02-06 21:31

Given an interface IService that has Method1() and Method2().

I want to test that when Method1() throws an Exce

相关标签:
2条回答
  • 2021-02-06 21:50

    You can do this with:

    var mock = new Mock<MyNetworkStream>(){ CallBase = true };
    mock.Setup(m => m.Method1....
    

    The above code will use the real implementation of MyNetworkStream for any method/property which is not explicitly setup. I.e. it'll call the real Method2(), while the Method1() will be the mocked version.

    CallBase=true is usually meant to test abstract classes (if this is right or wrong, is out of the scope of this question).

    0 讨论(0)
  • 2021-02-06 22:08

    In this case (unless there's a lot more going on) I would just create my own test class extending the class with the real behavior, that implements the interface you need to mock. This way you can mock the one value, and fallback to the base class for the real functionality.

    0 讨论(0)
提交回复
热议问题