Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it a best practice to always unit test the smallest possible unit of code? I find those tests will never survive a refactoring

I've been a practitioner of test driven development for several years, and overall i'm happy with it. The one part that I don't yet understand is the idea that you should always be unit testing the 'smallest possible unit'.

Part of the idea of unit testing seems to be to allow you to refactor with confidence that you won't break anything. However, I find that tests which test very small pieces of code will almost never survive these refactorings, the code always changes significantly enough that small unit tests just get thrown away and new tests are written. It is the tests that cover larger pieces of functionality that seem to give the most value here, since the higher level interfaces don't change as often.

And for trivial refactorings, like moving methods around, those are just done via an IDE, and since i'm using a staticly typed language, I've never run into a situation where the IDE isn't able to do the refactoring perfectly.

Anyone else have similar or opposite experiences?

like image 857
kwyjibo Avatar asked Sep 18 '09 17:09

kwyjibo


People also ask

What is unit testing why it is necessary to do the unit testing?

The main objective of unit testing is to isolate written code to test and determine if it works as intended. Unit testing is an important step in the development process, because if done correctly, it can help detect early flaws in code which may be more difficult to find in later testing stages.

Which type of test is used to test the smallest unit of code?

A unit test is a way of testing a unit - the smallest piece of code that can be logically isolated in a system. In most programming languages, that is a function, a subroutine, a method or property.


1 Answers

I've found the same thing - but one thing I think is important to differentiate is between private units of code, and publically accessible units of code. I do think that it is important to always unit test the "smallest possible, usable unit of code exposed in the public API".

The public API should not change during refactorings (since it breaks binary compatibility and versioning), so this issue does exist.

As for the private API, there's a balance here. The smaller you test, the more strongly you can rely on your tests. The higher level your tests become, the more flexible the tests are, and the more likely they are to survive a refactoring.

That being said, I believe both are important. A large scale refactoring will always require reworking tests - that's just part of testing in general.

like image 55
Reed Copsey Avatar answered Oct 03 '22 20:10

Reed Copsey