我的代码中有这行:
@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。我该怎么办?
您需要模拟您的http行为,因为ObjectMapper
不在范围内。发现WireMock在过滤HTTP流量和模拟响应方面符合您的目的
而不是从测试中抛出JsonProcessingException
,只是使ObjectMapper
实际上抛出了带有一些错误数据要处理的异常。