Why Mockito and Mockmvc don't work together?
-
I'm trying to some basic mock tests. I want to return my ApiResponse when Mockmvc call the API but it doesn't.
@RunWith(MockitoJUnitRunner.class) public class AuthControllerTest { @Autowired private MockMvc mockMvc; @InjectMocks AuthController authController; @Mock private AuthService authService; @Before public void init() { mockMvc = MockMvcBuilders.standaloneSetup(authController).build(); } @Test public void authenticateUserShouldReturnStatusOk() throws Exception { LoginRequest loginRequest = TestUtils.createLoginRequest(); AuthResponse authResponse = new AuthResponse("token", loginRequest.getUsername(), HttpStatus.OK); when(authService.authenticateUser(loginRequest)).thenReturn(authResponse); mockMvc.perform(post("/api/auth/login") .contentType(APPLICATION_JSON) .content(TestUtils.convertObjectToJsonBytes(loginRequest))) .andExpect(status().isOk()) .andDo(print()); verify(authService, times(1)).authenticateUser(refEq(loginRequest)); } }
MockMvc print result:
MockHttpServletRequest: HTTP Method = POST Request URI = /api/auth/login Parameters = {} Headers = [Content-Type:"application/json", Content-Length:"49"] Body = <no character encoding set> Session Attrs = {} MockHttpServletResponse: Status = 200 Error message = null Headers = [] Content type = null Body = Forwarded URL = null Redirected URL = null Cookies = [] Process finished with exit code 0
Why isn't that ApiResponse called? I want mockmvc to return the answer I gave, but nothing changes.
Can you help me?
-
Give it a try with this order.
Mockito.when(serviceMock.methodname(params)).thenReturn(responseType); String json = new Gson().toJson(param); MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.post(BASE_ENDPOINT) .content(json) .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON) .characterEncoding(CharEncoding.UTF_8); ResultActions resultActions = this.mockMvc.perform(requestBuilder); resultActions .andExpect(status().isOk()) .andExpect( MockMvcResultMatchers.jsonPath("$.fields").value(param.value()))); verify(serviceMock, times(1)).method(param);