我应该为每个断言创建一个新的测试方法吗? [英] Should I create a new test method for each assertion?

查看:28
本文介绍了我应该为每个断言创建一个新的测试方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这是主观的,但我想遵循最常见的做法.您通常为每个类方法创建一个测试方法并用多个断言填充它,还是为每个断言创建一个测试方法?

I know that this is subjective, but I'd like to follow the most common practice. Do you normally create one test method for each class method and stuff it with multiple assertions, or do you create one test method per assertion?

例如,如果我正在测试银行帐户的 withdraw 方法,并且我想确保在用户尝试透支帐户或提取负数时抛出异常,我应该创建testOverdawtestNegativeWithdrawal,还是我将这两个断言组合在一个名为 testWithdraw 的方法中?

For example, if I am testing a bank account's withdraw method, and I want make sure that an exception is thrown if the user tries to overdraw the account or withdraw a negative amount, should I create testOverdaw and testNegativeWithdrawal, or would I just combine those two assertions in a method called testWithdraw?

推荐答案

可以这样想:每个测试都应该独立运行并执行一组相对离散的功能.如果您想断言关于您创建的某个方法的三件事是否正确,那么您应该创建一个包含这三件事的测试.

Think of it this way: each test should stand on its own and exercise a relatively discrete set of functionality. If you want to assert whether three things are true about some method that you have created, then you should create a test that includes those three things.

因此,我不得不强烈反对其他已经回答的人.任意地将自己限制在每个测试的一个断言中对您没有任何帮助,只会使您的测试变得笨拙和乏味.最终它可能会让你完全放弃测试 - 这当然是一种耻辱:对你的项目和职业生涯不利.

Thus, I have to strongly disagree with the others who have answered. Arbitrarily limiting yourself to one assertion per test will do nothing for you except make your testing unwieldy and tedious. Ultimately it may put you off testing altogether - which would certainly be a shame: bad for your project and career.

现在,这意味着您有编写大型、笨拙或多用途测试例程的许可.确实,我认为我从来没有写过超过 20 行左右的文字.

Now, that does not mean you have license to write large, unwieldy or multi-purpose testing routines. Indeed, I don't think I've ever written one that is more than 20 lines or so.

当一个函数中有多个断言时,就知道哪个断言失败而言,您会注意到 nUnit 和 MSTest 都会在断言失败时为您提供描述和链接,这将使您直接进入违规行(nUnit 将需要集成工具,例如 TestDriven.net).这使得找出故障点变得微不足道.两者都将在函数中的第一次失败时停止,并且都使您能够进行调试演练.

As far as knowing which assertion fails when there are several in one function, you will note that both nUnit and MSTest give you both a description and a link when an assertion fails that will take you right to the offending line (nUnit will require an integration tool such as TestDriven.net). This makes figuring out the failure point trivial. Both will also stop on the first failure in a function and both give you the ability to do a debug walkthrough as well.

这篇关于我应该为每个断言创建一个新的测试方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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