問題描述
Rhino Mocks 存根和模擬僅適用于接口,而不適用于具體類,這對嗎?我花了很長時間試圖讓這段代碼正常工作.我沒想到存根的 pubSubClient 總是從類中調用 Send 方法.該方法有一些依賴并拋出異常.
Is it correct that Rhino Mocks stubs and mocks are only good for interfaces, not concrete classes? I spent quite a time trying to make this piece of code working. I did not expect the stubbed pubSubClient to always call Send method from the class. That method has some dependencies and throws exception.
[Test]
public void Test01()
{
PubSubMessage psm = new PubSubMessage();
var pubSubClient = MockRepository.GenerateStub<PubSubClient>();
pubSubClient.Stub(x => x.Send(psm)).IgnoreArguments().Return(null);
// actual PubSubClient Send method throws exception
// the rest of the test is skipped...
}
但是,當我提取接口并使用 IPubSubClient 運行相同的測試時,它似乎按預期工作.
However, when I have extracted the interface and run the same test with IPubSubClient, it seems to be working as expected.
這是否意味著我必須為我想用 Rhino 模擬/存根的每個類提取接口?還是我在技術上或概念上遺漏了什么?
Does it mean that I have to extract the interface for every class I want to mock/stub with Rhino? Or I am missing something, technically or conceptually?
更新:好的,看來我知道我遺漏了哪一部分:Rhino Mocks 無法攔截對非虛擬方法的調用.所以,我想我要么使用接口,要么使具體類上的每個方法都是虛擬的.如果還有其他選擇,請糾正我.
UPDATE: OK, It seems I figured out what part I was missing: Rhino Mocks cannot intercept calls to non-virtual methods. So, I guess I have either use interfaces or make every method on the concrete class virtual. Please correct me if there's another option.
推薦答案
Bryan 使用部分模擬的答案不正確.這不是部分模擬的用途.
Bryan's answer of using partial mocks is incorrect. That's not what partial mocks are for.
Jon Erickson 的回答基本正確:Rhino Mocks 和 Moq 無法攔截非虛擬調用,也無法攔截靜態方法或屬性.這意味著您不能偽造以下內容:
Jon Erickson's answer is mostly correct: Rhino Mocks and Moq can't intercept non-virtual calls, nor can they intercept static methods or properties. That means you can't fake the following:
DateTime.Now; // static property, can't fake static property
someClass.SomeNonVirtualMethod(); // can't fake non-virtual method
sealedClass.Foo(); // can't fake anything on sealed classes
Utilities.SomeStaticMethod(); // can't fake static methods
someList.Any(); // can't fake extension methods like Linq's .Any()
TypeMock 可以偽造這些,正如 Jon 提到的那樣.
TypeMock can fake these, as Jon mentioned.
需要注意的是,還有一個額外的模擬框架可以攔截所有調用:Microsoft Moles 框架.它的工作方式與 TypeMock 相同,它使用 .NET 分析器 API 來攔截調用.
It should be noted there is an additional mocking framework that can intercept all calls: the Microsoft Moles framework. It works the same way TypeMock does, it uses the .NET profiler API to intercept calls.
Moles 是免費的(目前).它也是測試版.Moles 僅適用于 Microsoft Pex 工具.而且它的 API 明顯不如 TypeMock 精致、優雅的 API.
Moles is free (for now). It's also beta. Moles only only works with Microsoft Pex tools. And its API is clearly inferior to TypeMock's refined, elegant API.
這篇關于Rhino Mocks 存根和模擬僅適用于接口?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!