【问题标题】:How to throw a JsonProcessingException with mockito如何用 mockito 抛出 JsonProcessingException
【发布时间】: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。我该怎么做?

【问题讨论】:

  • 能否添加两个类的完整代码,至少在控制器类中mapperAutowired 并显示测试类

标签: java spring-boot objectmapper


【解决方案1】:

您需要模拟您的 http 行为,因为 ObjectMapper 超出了范围。 Found WireMock 在过滤 http 流量和模拟响应方面符合您的目的

【讨论】:

    【解决方案2】:

    然后从测试中抛出JsonProcessingException 只是让ObjectMapper 实际上抛出带有一些虚假数据的异常来处理。

    【讨论】:

    • 我不能绑定虚假数据,因为如果我这样做,控制器会给我一个错误的请求
    【解决方案3】:

    你需要替换spring上下文中的Bean。

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

    然后你可以使用@MockBean 来做到这一点

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

    【讨论】:

    • @RunWith 是但 WebMVCTest 否,使用 WebMVCTest 执行会爆炸而不做任何测试
    • 好的,那么你如何在测试中设置mvc呢?你能把它加到上面的代码中吗?
    【解决方案4】:

    试试这个:

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

    【讨论】:

      【解决方案5】:
        doThrow(JsonProcessingException.class).when(object).method(...);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-05-22
        • 1970-01-01
        • 2014-04-06
        • 2023-02-07
        • 1970-01-01
        • 2018-07-02
        • 2023-03-06
        • 2017-04-20
        相关资源
        最近更新 更多