NullPointerException:无法调用“com.fasterxml.jackson.databind.ObjectMapper.writeValueAsString(Object)”,因为“this.objectMapper”为空

问题描述 投票:0回答:1

我的单元测试收到错误“this.objectMapper”为空”...我已使用 @Autowired 注释标记了 objectMapper。

java.lang.NullPointerException: Cannot invoke "com.fasterxml.jackson.databind.ObjectMapper.writeValueAsString(Object)" because "this.objectMapper" is null

    at com.santiang.demokadaiden.api.ProductCategoryMasterControllerTest.saveProductCategory(ProductCategoryMasterControllerTest.java:45)
    at java.base/java.lang.reflect.Method.invoke(Method.java:568)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
@ExtendWith(MockitoExtension.class)
public class ProductCategoryMasterControllerTest {

    @Mock
    private ProductCategoryMaster productCategoryMaster;
    @Autowired
    private MockMvc mockMvc;
    @Autowired
    private ObjectMapper objectMapper;

    @Test
    void saveProductCategory() throws Exception {
        ProductCategoryDTO categoryDTO = new ProductCategoryDTO();
        categoryDTO.setId(1L);
        categoryDTO.setName("Category 1");

        ProductCategory savedCategory = new ProductCategory(1L, "Category 1");

        given(productCategoryMaster.saveProductCategory(any(ProductCategory.class))).willReturn(savedCategory);

        mockMvc.perform(post("/api/product-categories")
                        .contentType(MediaType.APPLICATION_JSON)
                        .content(objectMapper.writeValueAsString(categoryDTO)))
                .andExpect(status().isCreated())
                .andExpect(jsonPath("$.id").value(1))
                .andExpect(jsonPath("$.name").value("Category 1"));
    }

任何人都可以帮我修改我的代码吗?

java spring unit-testing spring-boot-test objectmapper
1个回答
0
投票

objectMapper
从未初始化。您需要将
objectMapper
实例化为
new ObjectMapper
,然后您就可以调用它的方法。虽然它没有正确初始化,但它的值为
null
,即未知/未定义/nil,并且您无法调用
null
的方法。

© www.soinside.com 2019 - 2024. All rights reserved.