Integrate JUnit and Mockito, Unit Testing for Controller Layer

Teten Nugraha
Backend Habit
Published in
3 min readJan 29, 2020
Photo by Glenn Carstens-Peters 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 only on Controller Layer. 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. and on this article, I wil continue from my previous article https://medium.com/backend-habit/integrate-junit-and-mockito-unit-testing-for-service-layer-a0a5a811c58a

Lets Start..

create new file called UserControllerTest.java

@WebMvcTest(controllers = UserController.class)
@ActiveProfiles("test")
class UserControllerTest {

@Autowired
private MockMvc mockMvc;

@MockBean
private UserService userService;

private List<User> userList;

@BeforeEach
void setUp() {
this.userList = new ArrayList<>(); this.userList.add(new User(1L, "user1@gmail.com", "pwd1","User1")); this.userList.add(new User(2L, "user2@gmail.com", "pwd2","User2")); this.userList.add(new User(3L, "user3@gmail.com", "pwd3","User3"));

}
}

@MockMVCTest : annotation is used for Spring MVC tests. It disables full auto-configuration and instead apply only configuration relevant to MVC tests.

@MockMvc : is a class part of Spring MVC Test which help you to test controllers explicitly starting a Servlet container.

and then, we create dummy data on userList.

Test Fetch All User

Test Fetch 1 User By Id

Test 404 Response when access fetch 1 user by Id

Test Create New User

Test Create New User without Email filled

Test Delete One User by Id

for completed code, I stored on github and you can access to https://github.com/teten777/spring-boot-rest-api, and we will talk about how to generate code coverage report with Jacoco and sonarqube.

If it was interesting or helpful to you, please do press the 👏 clap button and help others find this story too or if you wanna talk internally with me , reach me in https://linktr.ee/teten_nugraha.

--

--

Teten Nugraha
Backend Habit

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