問題描述
我正在編寫一個依賴于擴展方法結果的測試,但我不希望該擴展方法未來的失敗會破壞這個測試.模擬該結果似乎是顯而易見的選擇,但 Moq 似乎沒有提供覆蓋靜態方法的方法(擴展方法的要求).Moq.Protected 和 Moq.Stub 也有類似的想法,但它們似乎沒有為這種情況提供任何東西.我是否遺漏了什么,或者我應該以不同的方式解決這個問題?
I am writing a test that depends on the results of an extension method but I don't want a future failure of that extension method to ever break this test. Mocking that result seemed the obvious choice but Moq doesn't seem to offer a way to override a static method (a requirement for an extension method). There is a similar idea with Moq.Protected and Moq.Stub, but they don't seem to offer anything for this scenario. Am I missing something or should I be going about this a different way?
這里是一個簡單的例子,失敗了通常的對不可覆蓋成員的無效期望".這是一個需要模擬擴展方法的壞例子,但它應該這樣做.
Here is a trivial example that fails with the usual "Invalid expectation on a non-overridable member". This is a bad example of needing to mock an extension method, but it should do.
public class SomeType {
int Id { get; set; }
}
var ListMock = new Mock<List<SomeType>>();
ListMock.Expect(l => l.FirstOrDefault(st => st.Id == 5))
.Returns(new SomeType { Id = 5 });
至于任何可能建議我使用 Isolator 的 TypeMock 愛好者:我很欣賞您的努力,因為看起來 TypeMock 可以蒙住眼睛和醉酒完成這項工作,但我們的預算不會很快增加.
As for any TypeMock junkies that might suggest I use Isolator instead: I appreciate the effort since it looks like TypeMock could do the job blindfolded and inebriated, but our budget isn't increasing any time soon.
推薦答案
擴展方法只是變相的靜態方法.Moq 或 Rhinomocks 等模擬框架只能創建對象的模擬實例,這意味著模擬靜態方法是不可能的.
Extension methods are just static methods in disguise. Mocking frameworks like Moq or Rhinomocks can only create mock instances of objects, this means mocking static methods is not possible.
這篇關于如何使用 Moq 模擬擴展方法?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!