单元测试时是否应该模拟所有依赖项? [英] Should I mock all the dependencies when unit testing?

查看:85
本文介绍了单元测试时是否应该模拟所有依赖项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的课程有一个依赖关系,我在单元测试中嘲笑了这个依赖关系.我在一个对我没有多大意义的地方得到了一个空引用异常.

My class has a dependency which I mocked in my unit tests. I was getting a null reference exception in a place where it didn't make much sense to me.

我只是意识到那是因为我没有设置我的模拟依赖.此依赖项已经过测试,但未连接到文件系统或数据源之类的任何东西.

I just realised it was because I didn't set up my mocked dependency. This dependency is tested but it doesn't connect to anything like file system or data sources.

我只想在这个新类中测试我的新代码,但是我猜在这种情况下最好完全不进行模拟.

I only wanted to test my new code in this new class but I guess in this case it is better not to mock at all.

这个结论正确吗?

推荐答案

正确.您应该嘲笑那些依赖于任何持久性或外部性的事物,以防止测试依赖于任何持久性或外部性.

Correct. You should mock things that depend on anything persistent or external in order to prevent the test from depending on anything persistent or external.

如果依赖项不依赖于任何持久性或外部性,则通过模拟获得的唯一好处是,即使依赖项错误,测试也可以正常工作-但这是假设该模拟工作正常.为此,您需要:

If the dependency does not depend on anything persistent or external, the only benefit you gain from mocking it is that the test will work properly even if the dependency is wrong - but that's assuming the mock works properly. For that you need to either:

  1. 编写一个完全模拟依赖关系的模拟程序.

  1. Write a mock that emulates the dependency completely.

编写一个模拟,以模拟将在测试中使用的特定情况下的依赖性.

Write a mock that emulates the dependency for the specific cases that will be used in the test.

第一个选择是完全荒谬的-为什么模拟应该比原始依赖更好?毕竟,可以肯定的是,在原始依赖项上的投入要比在模拟依赖项上投入的更多.

The first option is outright ridiculous - why should your mock be any better than the original dependency? After all, it's safe to assume much more effort was invested in the original dependency than in the mock...

第二个选项意味着您的模拟程序知道实现的确切细节-否则,您将不知道实现如何使用依赖项,因此您不知道如何模拟那些特定用途.这意味着测试不能满足单元测试的主要目的之一-在更改实现后验证代码是否可以正常工作.

The second option means your mock knows the exact details of the implementation - otherwise you won't know how the implementation uses the dependency so you don't know how to mock those specific uses. This means the test does not serve one of the main purposes of unit tests - verifying that the code works properly after changes to the implementation.

模仿的弊端太大而优势太小-特别是考虑到您可以始终运行依赖项的测试来检查其是否正常运行...

The drawbacks of mocking are too big and the advantages are too small - especially considering that you can always run the dependency's tests to check if it works properly...

这篇关于单元测试时是否应该模拟所有依赖项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆