Integrate JUnit and Mockito, Unit Testing for Service Layer

Teten Nugraha
Backend Habit
Published in
3 min readJan 16, 2020
Photo by Science in HD on Unsplash

On this article, we will talk about how to implement Unit Test and we will integrate unit test tool between JUnit and Mockito. But previously, I will using my code on article https://medium.com/backend-habit/membuat-rest-api-sederhana-dengan-spring-boot-part-iii-user-controller-9adb190ecae1

so, what is unit testing ?

Unit tests are typically automated tests written and run by software developers to ensure that a section of an application (known as the “unit”) meets its design and behaves as intended

so, we can explain that Unit Testing is to make sure how our code or every unit on our source code running well based on business process which is already defined.

Simple Case

Before I know about Unit Testing, I try on Web on Postman directly for search bug on my code using debugging mode for check every code I writed. and I think use this method is not effective, and my Senior told me that is some new method for using test, this is Unit Test, but in this case we will using JUnit and Mockito for unit test.

Lets Start..

create new file called UserServiceTest

@ExtendWith(MockitoExtension.class)
class UserServiceTest {

@Mock
private UserRepository userRepository;

@InjectMocks
private UserService userService;

}

We create this class extend with MockitoExtension, so dont need to declare MockitoAnnotations.initMocks(this) . We create using annotation based, because I think is very usefull.

@Mock : because on UserService have dependency to UserRepository, we create mock object to simulate behaviour of the real object.

@InjectMock : is create Object to inject mock dependency, because on this case we simulate about UserService, so we create @InjectMock based on UserService.

createUserSuccess Test
throw and exception unit test
update user test
test findAll
findUserById

Conclusion

Using Unit Test, We will confidence with our job because for now we know standar tool for Unit Test. On next article, I will tell you about how to unit test on Controller Layer. You can access https://medium.com/backend-habit/integrate-junit-and-mockito-unit-testing-for-controller-layer-91bb4099c2a5 directly.

--

--

Teten Nugraha
Backend Habit

Software Engineer, 8 years of experience. Expertise with Microservices, Spring Boot, CICD, Docker https://www.linkedin.com/in/teten-nugraha