boliveira
Welcome to my Social Blog
3y ago
Unit tests in Java
boliveira

Modern software development requires careful testing in order to "bake in" quality both during development time as well as deployment time, usually by running a pipeline on every commit, where unit tests are executed to make sure that the code being deployed is of high quality and contains no defects.

Let's look at some properties of unit tests and how to make sure they are leveraged to their full potential.


Properties of unit tests

Unit tests have some properties that must be followed so that they can be run as frequently as possible during development:

  • fast: unit tests need to be fast while running. Because each test is very self-contained, there can be dozens of thousands of tests within a project, so, speed is a priority for unit tests;

  • deterministic: it should be possible to run test suites locally as often as desired, and the results must be the same every time, because, if the underlying code implementation does not change, the tests should yield the same results;

  • self-contained: ideally, in a unit test, we want to test an atomic unit of code, i.e., a method, in such a way that all the required dependencies for that method are mocked such that only a very specific flow is under test;

  • complete: for maximum confidence in the test suite, we should have tests covering both the expected flows as well as unexpected ones, positive and negative cases, empty lists, single elements, etc.


JUnit in modern Java projects

JUnit can be used in modern Java projects, either using plain Java or frameworks like Spring or Springboot.

All it takes is to add JUnit as a dependency to your project and then tests can be declared as a separate class file.
As a quick tour, we can setup up methods to run before each test (or before all tests) and after, and tests are declared using a special annotation, as indicated below:

@BeforeEach / @BeforeAll

@AfterEach / @AfterAll

Finally, a test is declared as follows:

@Test void test() { .... }

0

Atomic Essay

Comments

What will you write today?

Write, publish, get feedback, and become a better writer.

Trusted by 75,000+ writers