gpt4 book ai didi

java - 如何使用mockito抛出JsonProcessingException

转载 作者:行者123 更新时间:2023-12-01 19:16:20 26 4
gpt4 key购买 nike

我的代码中有以下几行:

@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。我该怎么做?

最佳答案

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

关于java - 如何使用mockito抛出JsonProcessingException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59412688/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com