我们可以在单元测试中使用多个模拟对象吗?
我读过很多关于单元测试的文章。 大多数文章都说我们不应该在测试中使用多个模拟对象,但我不明白为什么。 有时,我们在测试中确实需要多个模拟对象。
I have read many articles about unit testing.
Most of the articles said that we should not use more than one mock object in a test, but i can't understand why.
Sometimes we really need more than one mock object in a test.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
根据上下文,您可以在单元测试中拥有多个模拟。
不过我认为“文章”可能暗示的是
You can have more than one mock in a unit test depending on the context.
However I think what 'the articles' might be hinting at is
您应该根据需要添加尽可能多的模拟来隔离您的测试类。 您需要为每个不应成为测试一部分的依赖项进行模拟。
有时,为了简单起见,您在测试中将两个或三个类放在一起,因为它们构建了类似组件的东西并且高度耦合。 其他一切都应该被嘲笑。
我知道这种“最佳实践”只有一个模拟,但也不理解它。 在我们的单元测试中,我们有很多模拟,一些环境模拟是由我编写的测试框架设置的(例如TransactionService,SecurityService,SessionService)。 只有一件事需要考虑,正如 Gishu 在他的回答中已经提到的那样,许多模拟表明高度依赖。 太多的时候就由你自己考虑了。 我们有很多小接口,在测试中需要很多mock。
为了扭转你的答案,你不应该在以下情况下模拟依赖项:
You should add as many mocks as necessary to isolate your class under test. You need a mock for every dependency that should not be part of the test.
Sometimes you put two or three classes together in a test, for simplicity, because they build something like a component and are highly coupled. Everything else should be mocked.
I know this "best practice" to have only one mock and also do not understand it. In our unit tests, we have many mocks, some environmental mocks are set up by the test framework I wrote (eg. TransactionService, SecurityService, SessionService). There is only one thing to consider, as Gishu already mentioned in his answer, many mocks are an indication of high dependency. It's up to you to consider when it is too much. We have many small interfaces, which requires many mocks in tests.
To turn your answer around, you should not mock a dependency when:
我不确定您指的是哪些文章,但我通常为被测类的每个依赖项都有一个模拟对象。
I'm not sure what articles you're referring to, but I typically have one mock object per dependency for the class under test.