問題描述
我想測試我班級的方法 A,但不調(diào)用通常由 A 調(diào)用的實際方法 B.這是因為 B 有很多外部交互,我現(xiàn)在不想測試.
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.
我可以為 B 調(diào)用的所有服務(wù)創(chuàng)建模擬,但這是相當(dāng)多的工作.我寧愿只是模擬 B 并讓它返回示例數(shù)據(jù).
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.
這可能與 Moq 框架有關(guān)嗎?
Is that possible to do with Moq framework?
推薦答案
是的,有一個問題!您必須確保方法 B
是虛擬的并且可以被覆蓋.
It is, with a catch!
You have to make sure method B
is virtual and can be overriden.
然后,將模擬設(shè)置為在未提供設(shè)置時調(diào)用基本方法.然后你設(shè)置B
,但不設(shè)置A
.因為沒有設(shè)置A
,實際的實現(xiàn)會被調(diào)用.
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
在幕后,Moq 將動態(tài)創(chuàng)建一個擴展 MyClass
并覆蓋 B
的類.
Behinds the scenes, Moq will dynamically create a class that extends MyClass
and overrides B
.
這篇關(guān)于在 Moq 中模擬被測主題的方法?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!