Spring MVC provides an integration testing utility named MockMvc. We can use this to write an integration test for REST API controller classes. Let's see how this works for the /account/<accountId> endpoint of the AccountController class:
package com.dineshonjava.bookshop.accountservice;
import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import com.dineshonjava.bookshop.accountservice.controller.AccountController;
import com.dineshonjava.bookshop.accountservice.domain.Account;
import com.dineshonjava.bookshop.accountservice.repository.AccountRepository;
@RunWith(SpringRunner.class)
@WebMvcTest(controllers = AccountController.class)
public class AccountControllerIntegrationTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private AccountRepository accountRepository;
@Test
public void shouldReturnFullName() throws Exception {
Account rushika = new Account(1003, "Rushika Rajput", "Noida", "9832XXX23", "rushika.raj@mail.com");
given(accountRepository.findAccountByAccountId(10003)).willReturn(rushika);
mockMvc.perform(get("/account/10003"))
.andExpect(content().string("Hello Rushika Rajput!"))
.andExpect(status().is2xxSuccessful());
}
}
In the preceding integration test class, we defined a test method for the findAccountById() method of the AccountController class by using the MockMvc framework. In the preceding class, we used the @WebMvcTest annotation to tell Spring which controller we're testing. We also used the @MockBean annotation to mock the AccountRepository class in our Spring context.