问题描述
我使用过编写了 NUnit 测试的代码.但是,我从未使用过模拟框架.这些是什么?我了解依赖注入以及它如何帮助提高可测试性.我的意思是在单元测试时可以模拟所有依赖项.但是,那为什么我们需要模拟框架呢?我们不能简单地创建模拟对象并提供依赖项.我在这里错过了什么吗?谢谢.
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.
推荐答案
- 它使模拟更容易
- 他们通常让你表达可测试提到的断言对象之间的交互.
这里有一个例子:
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 方法被调用并且输入参数是上下文对象.如果没有发生,我的测试就会失败.
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.
这篇关于为什么我们需要模拟框架?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!