[英]How to throw a JsonProcessingException with mockito
i have this lines in my code:我的代码中有这一行:
@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);
}
My model Prueba.java我的模型Prueba.java
public class Prueba {
@Id
private String nombre;
private String apellidos;
private String edad;
}
And in test i want to force the JsonProcessingException but i can´t.在测试中我想强制 JsonProcessingException 但我不能。 I already try this:
我已经尝试过这个:
@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());
}
But always the response is a 200 OK.但总是响应是 200 OK。 How can i do this?
我怎样才能做到这一点?
而不是从测试中抛出JsonProcessingException
只是让ObjectMapper
实际上抛出该异常并带有一些要处理的错误数据。
You need to replace the Bean in the spring context.您需要替换 spring 上下文中的 Bean。
I assume you use Spring Boot with @RunWith(SpringRunner.class) and @WebMVCTest?我假设您将 Spring Boot 与 @RunWith(SpringRunner.class) 和 @WebMVCTest 一起使用?
Then you can do this using @MockBean然后你可以使用@MockBean 来做到这一点
See also: https://www.baeldung.com/java-spring-mockito-mock-mockbean另见: https : //www.baeldung.com/java-spring-mockito-mock-mockbean
尝试这个:
Mockito.doThrow(JsonProcessingException.class).when(this.mapperMock).writeValueAsString(Mockito.any());
doThrow(JsonProcessingException.class).when(object).method(...);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.