Mock a method of the subject under test in Moq?

前端 未结 1 1814
暖寄归人
暖寄归人 2021-02-12 08:55

I want to test method A of my class, but without calling the actual method B which is normally called by A. That\'s because B has a lot of external interactions I don\'t want to

1条回答
  •  野性不改
    2021-02-12 09:32

    It is, with a catch! You have to make sure method B is virtual and can be overriden.

    Then, set the mock to call the base methods whenever a setup is not provided. Then you setup B, but don't setup A. Because A was not setup, the actual implementation will be called.

    var myClassMock = new Mock();
    myClassMock.Setup(x => x.B()); //mock B
    
    myClassMock.CallBase = true;
    
    MyClass obj = myClassMock.Object;
    obj.A(); // will call the actual implementation
    obj.B(); // will call the mock implementation
    

    Behinds the scenes, Moq will dynamically create a class that extends MyClass and overrides B.

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