Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How many unit tests should I write per function/method?

Tags:

unit-testing

Do you write one test per function/method, with multiple checks in the test, or a test for each check?

like image 293
andreas buykx Avatar asked Sep 21 '08 06:09

andreas buykx


People also ask

Should I write a unit test for every method?

The answer to the more general question is yes, you should unit test everything you can. Doing so creates a legacy for later so changes down the road can be done with peace of mind. It ensures that your code works as expected.

Should unit tests only test one method?

This guideline is much more aggressive and recommended if you work in a test driven manner rather than write the tests after the code has been written. The main goal here is better code coverage or test coverage.

How much unit testing is enough?

It isn't realistic -- or necessary -- to expect 100% code coverage through unit tests. The unit tests you create depend on business needs and the application or applications' complexity. Aim for 95% or higher coverage with unit tests for new application code.

How often should you run unit tests?

A best practice is to run unit tests as part of a nightly build process. Show activity on this post. Ideally the unit tests should be run as part of every build and prior to every check in of changed code. However, with a large number of tests this can take a significant time, so you need to be able to manage that.


Video Answer


2 Answers

One test per check and super descriptive names, per instance:

@Test public void userCannotVoteDownWhenScoreIsLessThanOneHundred() {  ... } 

Both only one assertion and using good names gives me a better report when a test fails. They scream to me: "You broke THAT rule!".

like image 91
marcospereira Avatar answered Sep 22 '22 23:09

marcospereira


I have a test per capability the function is offering. Each test may have several assertions, however. The name of the testcase indicates the capability being tested.

Generally, for one function, I have several "sunny day" tests and one or a few "rainy day" scenario, depending of its complexity.

like image 40
philant Avatar answered Sep 19 '22 23:09

philant