問題描述
我使用過編寫了 NUnit 測試的代碼.但是,我從未使用過模擬框架.這些是什么?我了解依賴注入以及它如何幫助提高可測試性.我的意思是在單元測試時(shí)可以模擬所有依賴項(xiàng).但是,那為什么我們需要模擬框架呢?我們不能簡單地創(chuàng)建模擬對象并提供依賴項(xiàng).我在這里錯(cuò)過了什么嗎?謝謝.
I have worked with code which had NUnit test written. But, I have never worked with mocking frameworks. What are they? I understand dependency injection and how it helps to improve the testability. I mean all dependencies can be mocked while unit testing. But, then why do we need mocking frameworks? Can't we simply create mock objects and provide dependencies. Am I missing something here? Thanks.
推薦答案
- 它使模擬更容易
- 他們通常讓你表達(dá)可測試提到的斷言對象之間的交互.
這里有一個(gè)例子:
var extension = MockRepository
.GenerateMock<IContextExtension<StandardContext>>();
var ctx = new StandardContext();
ctx.AddExtension(extension);
extension.AssertWasCalled(
e=>e.Attach(null),
o=>o.Constraints(Is.Equal(ctx)));
你可以看到我明確地測試了 IContextExtension 的 Attach 方法被調(diào)用并且輸入?yún)?shù)是上下文對象.如果沒有發(fā)生,我的測試就會(huì)失敗.
You can see that I explicitly test that the Attach method of the IContextExtension was called and that the input parameter was said context object. It would make my test fail if that did not happen.
這篇關(guān)于為什么我們需要模擬框架?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!