A typical unit test contains 3 phases: First, it initializes a small piece of an application it wants to test (also known as the system under test, or SUT), then it applies some stimulus to the system under test (usually by calling a method on it), and finally, it observes the resulting behavior. We will see that writing unit tests and generating testable code is not just about making testing less troublesome, but about making the code itself more robust, and easier to maintain.Įssentially, a unit test is a method that instantiates a small portion of our application and verifies its behavior independently from other parts. We will discuss what makes code hard to test, which anti-patterns and bad practices we should avoid to improve testability, and what other benefits we can achieve by writing testable code. In this unit testing tutorial, I intend to demonstrate that unit tests are quite easy the real problems that complicate unit testing, and introduce expensive complexity, are a result of poorly-designed, untestable code. Having difficulty testing their own or someone else’s code, developers often think that their struggles are caused by a lack of some fundamental testing knowledge or secret unit testing techniques.
However, it can sometimes be quite difficult to write a good unit test for a particular piece of code.
Unit testing is an essential instrument in the toolbox of any serious software developer.