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

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

问题描述

我的班级有一个我在单元测试中模拟的依赖项.我在一个对我来说没有多大意义的地方得到了一个空引用异常.

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. 编写一个完全模拟依赖的mock.

  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...

第二个选项意味着您的 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天全站免登陆