Monday, December 6, 2010

The Essence of Unit Testing

Unit testing is about making sure software works at the function or method level. The act is taken upon by developers and is seen as a protective net to catch the unit-level bugs before integration...

By definition, a unit test is an automated piece of code that invokes the method or class being tested and then checks some assumptions about the logical behavior of that method or class. Here logical code means code having an IF statement, a loop, switch, some sort of calculation, or decision making code. (referenced from the book "The Art of Unit Testing").

The book goes on to point out properties of a good unit test are:
  • It should be automated and repeatable
  • It should be easy to implement
  • Once it’s written, it should remain for future use
  • Anyone should be able to run it
  • It should run at the push of a button
  • It should run quickly
Then it differentiate integration testing from unit testing. A unit test exercises and tests only a single unit in isolation whereas integration testing exercises verification on two or more dependent software modules.

Why unit test you may ask. Some answers include:
  • Helps find problems early in the development cycle
  • Facilitates changes with regression testing being automated
  • Simplifies integration testing
  • Provides a living documentation
  • Allows for test-driven development (TDD)
There are some minor drawbacks:
  • Can only show the presence of errors not the absence (like all testing)
  • By definition cannot catch integration or performance errors
  • Time and effort needed, e.g. for more features… others?
But overall, some unit testing are still necessary since the benefits usually outweigh the drawbacks.

Recommended Unit Testing framework in the C++ world: GoogleTest + GoogleMock.