![]() |
VOOZH | about |
Test Driven Development (TDD) is a software development approach where tests are written before the actual code implementation. Using JUnit 5 and Mockito, developers can create reliable and maintainable applications by validating behavior early. This approach improves code quality, reduces bugs, and ensures better design through continuous testing.
This section demonstrates how to set up a Maven-based Java project and systematically write unit tests using JUnit 5 along with Mockito to mock dependencies and verify application behavior effectively.
Create a Maven project using your IDE or command line.
Include dependencies for JUnit 5, assertions, and testing tools.
pom.xml
Project Structure:
Create basic POJO classes:
BaseEntity.java
BaseEntityfirstName, lastNameGeek.java
Author.javaGeekaddress, city, telephoneAuthorType.javaAuthorServiceAuthorController.java
Define repository interface:
AuthorRepository.java
Define service interface and implementation.
AuthorService.java: Defines business methods
AuthorMapService.java: Implements service using in-memory storage
ControllerTests.java: Runs once before all tests
ModelRepeatedTests.java: Supports repeated test execution
ModelTests.java:Runs before each test
AuthorTest.java:
Here we can see that can include more than one annotations
It helps to go with @ValueSource. @EmptySource and @NullSource represent a single parameter. On running the above code, we can able to get the below output
GeekTest.java
On running the above, the first test is ok and second one fails as expected and the actual one does not match
AuthorMapServiceTest.java
@BeforeEach -> setup before every test @Nested -> group related tests @DisplayName -> readable test namesmvn test