This page shows how you best write unit tests in inspectIT
Tooling
These are the tools we are using for testing:
- TestNG: As testing framework. We decided to move from junit to testNG some years ago when junit seemed to be stuck
- Mockito: To allow easy mock-based testing.
- Hamcrest: To allow to read the asserts in a human-understandable way.
Testing a spring-based service
Actually this is the situation that you very often will write unit tests. You created or extended a service and want to ensure that it is working. So this is what you want to do:
- Create a class that mirrors the package structure of your testee, call the class like the Testee and put Test at the end. Normal source code belongs in the src folder, test code go to the test folder (the test for info.inspectit.service.VersionService is thus info.inspectit.service.VersionServiceTest)
- Extend from info.novatec.inspectit.testbase.TestBase
- Each method should test exactly one situation, prefer to write more test methods than to have everything within one method
Here is an example:
The VersionService uses a VersionProvider to retrieve the current version. The Provider is responsible for retrieving the version in some way and returning the string back to the version service which will build up a nice representation of the version (or throw exceptions if the version is invalid). Realizations can be for example the FileBasedVersionReader
The VersionServiceTest mirrors the package structure of the VersionService. It extends TestBase. The Versionservice is responsible for caching the version lookup, so one test method checks that correct versions are cached. To do that the VersionProvider is mocked. Notice the InjectMocks annotation on the versionService (the testee) to integrate all mocks automatically.