如何使用Mockito

时间:2019-12-19 15:27:58

标签: java spring-boot objectmapper

我的代码中有以下几行:

@Autowired
private ObjectMapper mapper = new ObjectMapper();

@PostMapping("/postPrueba")
public ResponseEntity<String> postPrueba(@RequestBody Prueba prueba) {

    String pTest = null;
    try {
        pTest  = mapper.writeValueAsString(prueba);
        System.out.println(pTest  );
    } catch (JsonProcessingException e) {
        return new ResponseEntity<>("", HttpStatus.INTERNAL_SERVER_ERROR);
    }
        return new ResponseEntity<>("", HttpStatus.OK);
}

我的模型 Prueba.java

public class Prueba {

    @Id
    private String nombre;
    private String apellidos;
    private String edad;
}

在测试中,我想强制JsonProcessingException,但我不能。我已经尝试过了:

@Mock
private ObjectMapper mapperMock;

@Test
public void testKo() throws Exception {

    ObjectMapper om = Mockito.spy(new ObjectMapper());
    Mockito.when(this.mapperMock.writeValueAsString(Mockito.any())).thenThrow(new JsonProcessingException("") {});

    ObjectMapper om = Mockito.spy(new ObjectMapper());
    Mockito.when( om.writeValueAsString(Mockito.eq(Prueba.class))).thenThrow(new JsonProcessingException("") {});

    Mockito.when(this.mapperMock.writeValueAsString(Mockito.eq(Prueba.class))).thenThrow(new JsonProcessingException("") {});

    String jsonContent = "{'nombre': '123456', 'apellidos': '12'}";
    jsonContent = jsonContent.replaceAll("\'", "\"");

    this.mvc.perform(post("/postPrueba")
                .contentType(MediaType.APPLICATION_JSON)
                .content(jsonContent))
                .andExpect(status().is5xxServerError());
    }

但总是响应为200 OK。我该怎么办?

5 个答案:

答案 0 :(得分:0)

您需要模拟您的http行为,因为ObjectMapper不在范围内。找到的WireMock在过滤http流量和模拟响应方面符合您的目的

答案 1 :(得分:0)

与其将JsonProcessingException从测试中抛出,不如实际上使ObjectMapper抛出该异常以及一些要处理的错误数据。

答案 2 :(得分:0)

您需要在spring上下文中替换Bean。

我假设您将Spring Boot与@RunWith(SpringRunner.class)和@WebMVCTest一起使用?

然后您可以使用@MockBean

另请参阅:https://www.baeldung.com/java-spring-mockito-mock-mockbean

答案 3 :(得分:0)

尝试一下:

Mockito.doThrow(JsonProcessingException.class).when(this.mapperMock).writeValueAsString(Mockito.any());

答案 4 :(得分:0)

  doThrow(JsonProcessingException.class).when(object).method(...);