Mastering Unit Testing Using Mockito and JUnit
上QQ阅读APP看书,第一时间看更新

Defining unit testing

A test is an assessment of our knowledge, a proof of concept, or an examination of data. A class test is an examination of our knowledge to ascertain whether we can go to the next level. For software, it is the validation of functional and nonfunctional requirements before it is shipped to a customer.

Unit testing code means validation or performing the sanity check of code. Sanity check is a basic test to quickly evaluate whether the result of a calculation can possibly be true. It is a simple check to see whether the produced material is coherent.

It's a common practice to unit test the code using print statements in the main method or by executing the application. Neither of them is the correct approach. Mixing up production code with tests is not a good practice. Testing logic in the production code is a code smell, though it doesn't break the code under the test. However, this increases the complexity of the code and can create severe maintenance problem or cause system failure if anything gets misconfigured. Print statements or logging statements are executed in the production system and print unnecessary information. They increase execution time and reduce code readability. Also, junk logging information can hide a real problem, for instance, you may overlook a critical deadlock or a hung thread warning because of excessive logging of junk.

Unit testing is a common practice in test-driven development (TDD). TDD is an evolutionary development approach. It offers test-first development where the production code is written only to satisfy a test, and the code is refactored to improve its quality. In TDD, unit tests drive the design. You write code to satisfy a failing test, so it limits the code you write to only what is needed. The tests provide a fast, automated regression for refactoring and new enhancements.

Kent Beck is the originator of Extreme Programming and TDD. He has authored many books and papers.

Generally, all tests are included in the same project but under a different directory/folder. Thus, a org.packt.Bar.java class will have a org.packt.BarTest.java test. These will be in the same package (org.packt) but will be organized in the: src/org/foo/Bar.java and test/org/foo/BarTest.java directories, respectively.

Our customers do not execute the unit tests, so we don't deliver the test source folder to them. Having the code and test in the same package allows the test to access protected and default methods/properties. This is particularly useful while working with the legacy code.

Java code can be unit tested using a code-driven unit testing framework. The following are a few of the available code-driven unit testing frameworks for Java:

  • SpryTest
  • Jtest
  • JUnit
  • TestNG

JUnit is the most popular and widely used unit testing framework for Java. We will explore JUnit 4 in the next section.