Unit testing is a crucial aspect of software development, ensuring that individual application components behave as expected. This project was used for me to learn how to implement unit tests using JUnit and Mockito in a Spring Boot environment.
The project utilizes the following dependencies:
- JUnit 5: For writing and running unit tests.
- Mockito: For mocking dependencies and behavior verification.
- Spring Boot Starter Data JPA: For accessing relational databases.
- Spring Boot Starter Web: For building web applications.
- H2 Database: An in-memory database for development and testing purposes.
- Spring Boot Starter Test: For testing Spring Boot applications.
To run the unit tests, you can use your favorite IDE or run the following Maven command:
mvn test
This command will execute all the unit tests defined in the project and provide detailed output regarding the test results.
-
testFindByUserName: Tests the
findByUsername
method of theUserService
class by mocking theUserRepository
dependency. Verifies that the method returns the expected user object when a valid username is provided. -
testSaveUser: Tests the
save
method of theUserService
class by mocking theUserRepository
dependency. Verifies that the method correctly saves a user object and returns the saved user with the expected attributes. -
testUpdateUserWhenUserAlreadyExists: Tests the
update
method of theUserService
class by mocking theUserRepository
dependency. Verifies that the method updates an existing user object with the provided data. -
testDeleteUserWhenUserExists: Tests the
delete
method of theUserService
class by mocking theUserRepository
dependency. Verifies that the method deletes a user when the user exists. -
testDeleteUserWhenUserDoesNotExist: Tests the
delete
method of theUserService
class by mocking theUserRepository
dependency. Verifies that the method throws aUserException
when attempting to delete a non-existent user.
Author: Jonas Dias | Social Media | Thank You