如何对依赖于许多其他类的类进行单元测试? [英] How do you unit test a class that is dependent on many other classes?

查看:29
本文介绍了如何对依赖于许多其他类的类进行单元测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直听说通过单元测试我们可以捕获代码中的大部分错误,我真的相信这是真的.但我的问题是在每个类都依赖于许多其他类的大型项目中,您如何对类进行单元测试?由于复杂性和编写存根所需的时间,因此删除所有其他类没有多大意义.您对此有何看法?

I have been hearing that with unit testing we can catch most of the bugs in the code and I really believe that this is true. But my question is in large projects where each class is dependent on many other classes how do you go about unit testing the class ? Stubbing out every other class doesn't make much sense because of both complexity and the time required to write the stubs. What is your opinion about it?

推荐答案

使用测试的部分优势在于它迫使您最小化依赖关系,从而创建可测试的代码.通过最小化依赖性,您将提高代码的可维护性和可重用性,这两个都是非常理想的特性.

Part of the advantage of using tests, is that it forces you to minimize dependencies thereby creating testable code. By minimizing dependencies you will increase maintainability and reusability of your code, both highly desirable traits.

由于您将测试引入现有代码库,您无疑会遇到许多难以测试的情况,需要重构才能正确测试.这种重构将提高代码的可测试性,同时减少依赖性.

Since you are introducing tests into an existing code-base, you will no doubt encounter many hard-to-test situations which will require refactoring to test properly. This refactoring will increase the testability of your code, decreasing dependencies at the same time.

难以用测试改造代码的原因是许多人提倡遵循测试驱动开发的原因.如果您先编写测试,然后编写代码以通过测试,则默认情况下您的代码将更加可测试和解耦.

The reason why its hard to retrofit code with tests is why many advocate following Test-Driven-Development. If you write your tests first and then write the code to pass the tests, your code will by default be much more testable and decoupled.

这篇关于如何对依赖于许多其他类的类进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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