【问题标题】:Spring Boot unit testing assertion error JSON object got a JSON arraySpring Boot 单元测试断言错误 JSON 对象得到一个 JSON 数组
【发布时间】:2021-07-28 00:15:26
【问题描述】:

我在 Spring Boot 应用程序中进行单元测试。但是由于 getProductById() 方法返回对象的 Optional,我不确定如何测试它。

ProductController.java

@GetMapping("/products/{id}")
@Transactional(readOnly=true)
@Cacheable("product-cache")
public Product getProduct(@PathVariable("id") int id) {
        LOGGER.info("Finding product by id : "+id);
        return productRepository.findById(id).get();
}

MockTest.java

private static final String PRODUCTS_URL = "/productsapi/products";
private static final int PRODUCT_ID = 1;
private static final String CONTEXT_URL = "/productsapi";
private static final int PRODUCT_PRICE = 1000;
private static final String PRODUCT_DESCRIPTION = "Its awesome";
private static final String PRODUCT_NAME = "Macbook";

@Test
public void testGetProductById() throws JsonProcessingException, Exception {
        Product product = buildProduct();
        when(productRepository.findById(PRODUCT_ID)).thenReturn(Optional.of(product));
        
        ObjectWriter objectWriter = new ObjectMapper().writer().withDefaultPrettyPrinter();
        mockMvc.perform(get(PRODUCTS_URL).contextPath(CONTEXT_URL))
           .andExpect(status().isOk())
           .andExpect(content().json(objectWriter.writeValueAsString(Optional.of(product))));
}

private Product buildProduct() {
        Product product = new Product();
        product.setId(PRODUCT_ID);
        product.setName(PRODUCT_NAME);
        product.setDescription(PRODUCT_DESCRIPTION);
        product.setPrice(PRODUCT_PRICE);
        return product;
}

当我运行测试时,它失败并出现以下错误。

错误: java.lang.AssertionError: 预期:一个 JSON 对象 得到:一个 JSON 数组

它没有显示任何编译错误。但是测试用例失败了。我认为这是将产品对象转换为 json 的问题。

所以,解决这个问题的帮助不大!

【问题讨论】:

    标签: java spring-boot unit-testing junit optional


    【解决方案1】:

    控制器方法仅返回 Product 对象,它是一个 JSON {},并且在您使用 JSON [{}] 数组断言的 andExpect 方法中,删除 Optional 并仅传递产品对象

    mockMvc.perform(get(PRODUCTS_URL).contextPath(CONTEXT_URL)).andExpect(status().isOk())
                .andExpect(content().json(objectWriter.writeValueAsString(product)));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-04
      • 2019-04-26
      • 2019-03-27
      • 2016-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-31
      相关资源
      最近更新 更多