Skip to content

Unit Testing

BrunoRosendo edited this page Aug 30, 2023 · 2 revisions

Similar to any software project, unit testing is a practice where individual components or units of code are tested in isolation to ensure they function as intended. In our project, this practice is primarily applied to modest utility functions (like model functions) and custom annotations (such as validation).

Conversely, complex procedures like repository management within services and controllers are better suited for Integration Testing, as unit testing might prove challenging in those instances.

Contents

How to Create Unit Tests

Our unit tests adhere to the JUnit framework, a widely adopted testing tool. If you're unfamiliar, it's recommended to consult its documentation or various online tutorials for learning. In this guide, we'll furnish an example and look at the most prevailing features used within the project.

All testing procedures reside in the test/ package, mirroring the main code's structure, simplifying the correlation between the testing and corresponding classes. The tests within the controller/ package, despite contributing significantly to test coverage, are not classified as unit tests but integration tests.

To illustrate, consider the custom date validator example:

internal class DateIntervalTest {
    @Test
    fun `should succeed when endDate is null`() {
        val validator = DateIntervalValidator()
        validator.initialize(ValidDateInterval())
        assert(
            validator.isValid(
                DateInterval(
                    TestUtils.createDate(2022, 12, 6),
                    null
                ),
                null
            )
        )
    }
}

When crafting tests, bear in mind these crucial points:

  • All test classes should be internal to prevent their use outside other modules.
  • Employ the @Test annotation for all tests and employ assertions to validate the test objectives.
  • Kotlin allows the use of spaces for the function's name. This is useful for test descriptions but isn't recommended for regular code. Alternatively, you can use @DisplayName to change the description.
  • Numerous beneficial JUnit annotations are accessible, particularly @BeforeEach, @BeforeAll, @AfterEach, and @AfterAll.

It's worth noting that IntelliJ provides many testing-centric features, so we encourage you to delve into their utility.

Note: If needed, you can read about mocks in Integration Testing - Mocking.