Unit tests

"There are two parts to learning craftsmanship: knowledge and work." - Robert C. Martin

Unit tests

testy jednostkowe

Unit tests is a set of tests that allow you to verify the unit of the production code. The unit of such code can be a class, a module, a method. It is important that one test verify only one functionality. Each test should consist of three basic sections: “given”, “when”, “then”. The “given” section should contain the so-called scenario, thus creating a class object with specific parameters. The “when” section should include, for example, calling the tested method. In turn, the last “then” section should contain at most several assertions that compare the results obtained with the test method with the expected results. Below is an example test for a program converting Roman numerals into Arabic numerals.

 
//given 
RomanNumeral roman = new RomanNumeral("XIV"); 

//when 
int number = roman.convert(); 

//then 
Assert.assertEquals(14, number); 

Unit tests are an inseparable part of one of the agile TDD programming techniques, i.e. Test Driven Development. Creating software using this technique comes down to three basic steps. First, the programmer writes a test checking the new functionality without its implementation, at this stage the test should fail. Next, the programmer implements this functionality, the test should work. In the last step, the programmer refactorizes the code. According to this programming technique, the test code is just as important as the production code.

Why do we write tests? The answer is simple – to avoid mistakes! Poorly tested software may have disastrous consequences, which often do not come down to the user’s frustration, but also to lost money! Writing tests on a regular basis not only allows you to avoid errors, but also helps to eliminate the so-called regression – as the application develops, new functionalities are added and what previously worked correctly can simply stop working.

Writing tests often takes almost as much time as writing a production code. Nevertheless, writing tests allows early detection of errors and improvement of them still at the creation stage, and not after the release of the program for use. The time lost in writing tests for each new functionality is nothing compared to the time lost in debugging the entire program, containing thousands of different functionalities in search of one bug. Every programmer putting the application to use should be sure that it works correctly!