【问题标题】:Why Mockito and Mockmvc don't work together为什么 Mockito 和 Mockmvc 不能一起工作
【发布时间】:2020-12-31 00:12:01
【问题描述】:

我正在尝试一些基本的模拟测试。我想在 Mockmvc 调用 API 时返回我的 ApiResponse,但它没有。

@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 打印结果:

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

为什么不调用 ApiResponse?我希望 mockmvc 返回我给出的答案,但没有任何改变。

你能帮帮我吗?

【问题讨论】:

    标签: spring spring-boot testing junit mockito


    【解决方案1】:

    试试这个订单。

     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);
    

    【讨论】:

    • API 请求有效,但似乎仍然没有响应。 Response = "MockHttpServletResponse: Status = 200 错误消息 = null Headers = [] Content type = null Body = Forwarded URL = null Redirected URL = null Cookies = [] "
    猜你喜欢
    • 1970-01-01
    • 2020-03-04
    • 2016-01-04
    • 1970-01-01
    • 1970-01-01
    • 2020-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多