Teten Nugraha



Integrate JUnit and Mockito, Unit Testing for Service Layer

Integrate JUnit and Mockito, Unit Testing for Service Layer

Teten Nugraha's photo
Teten Nugraha
·Jan 16, 2020·

2 min read

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

class UserServiceTest {

    private UserRepository userRepository;

    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 TestcreateUserSuccess Test

throw and exception unit testthrow and exception unit test

update user testupdate user test

test findAlltest findAll



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.

Did you find this article valuable?

Support Teten Nugraha by becoming a sponsor. Any amount is appreciated!

Learn more about Hashnode Sponsors
Share this