Mock a method of the subject under test in Moq?

只谈情不闲聊 提交于 2019-12-21 07:06:41

问题


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 test for now.

I could create mocks for all the services called by B, but that's quite some work. I'd rather just mock B and make it return sample data.

Is that possible to do with Moq framework?


回答1:


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<MyClass>();
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.



来源:https://stackoverflow.com/questions/21460834/mock-a-method-of-the-subject-under-test-in-moq

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!