Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I create a new test method for each assertion?

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?

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?

like image 871
ryeguy Avatar asked Dec 14 '09 00:12

ryeguy


2 Answers

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.

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.

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.

like image 175
Mark Brittingham Avatar answered Oct 27 '22 00:10

Mark Brittingham


Personally I would create one test for each assertion otherwise you have to dig to find the reason for the failure rather than it being obvious from the test name.

If you have to write a few lines of code to set up a test and don't want to duplicate that then depending on your language and test framework you should be able to create a set of tests where each test will execute a block of code before it runs.

like image 34
cletus Avatar answered Oct 26 '22 22:10

cletus