Unit Testing – Should Each Unit Test Be Run Independently?

tddtestingunit testing

Say you have tests for two methods of a class. The first method gathers data from another tier and puts it into some sort of storage independent of the runtime (such as a SQL table), so all of the data handled by this test is hardcoded into the test. The second method is responsible for taking data from where the first method left it and transforming it in some way (calculation, moving certain parts elsewhere, etc.).

Now this second method could have hardcoded inputs like the first one, or it could be assumed that the two tests would be run sequentially and it could pick up where the 1st test left off, taking the data that was really stored by the first test.

If you went with the second option, you would really have a good idea that the two methods play well together, however, if the 1st test failed, all tests after it would fail, taking away testing benefit of helping to isolate bugs more quickly.

If you went with the first option, each method would be isolated and tested independently, but you would never really know that they can really work together properly.

Which is the better option here? Is there some sort of alternative like having a single test for each isolated method with hardcoding, and then bigger tests that contain both methods in one?

Best Answer

If you went with the first option, each method would be isolated and tested independently, but you would never really know that they can really work together properly.

If your methods are truly independent this shouldn't matter. Your second method should:

a) Work correctly when presented with valid data.

b) Fail sensibly and consistently when presented with invalid data.

Equally your first method should do the same. So as long as you handle the error cases they will work together properly.

If you want to test that the methods work correctly together then that's integration testing, not unit testing.