samedi 12 septembre 2020

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?

Aucun commentaire:

Enregistrer un commentaire