【发布时间】:2019-12-19 15:27:58
【问题描述】:
我的代码中有这几行:
@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。我该怎么做?
【问题讨论】:
-
能否添加两个类的完整代码,至少在控制器类中
mapper是Autowired并显示测试类
标签: java spring-boot objectmapper