You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

单元测试中ObjectMapper注入为空引发空指针异常,求技术支持

解决单元测试中ObjectMapper为Null的问题

问题根源

你的测试类使用了@ExtendWith(MockitoExtension.class),这个扩展仅负责创建Mockito的Mock对象,不会加载Spring应用上下文。因此@Autowired标注的ObjectMapper和MockMvc无法被Spring容器实例化,导致空指针异常。

解决方案

方案一:使用Spring Boot WebMvc测试扩展(推荐)

改用@WebMvcTest注解,它会加载Web层的Spring上下文,自动配置MockMvc和ObjectMapper,同时用@MockBean来Mock业务层组件:

@WebMvcTest(ProductCategoryMasterController.class)
public class ProductCategoryMasterControllerTest {

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

    @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"));
    }
}

方案二:手动实例化对象(轻量测试)

如果不想加载Spring上下文,可手动创建ObjectMapper并初始化MockMvc:

@ExtendWith(MockitoExtension.class)
public class ProductCategoryMasterControllerTest {

    @Mock
    private ProductCategoryMaster productCategoryMaster;
    private MockMvc mockMvc;
    private ObjectMapper objectMapper = new ObjectMapper();

    @BeforeEach
    void setUp() {
        ProductCategoryMasterController controller = new ProductCategoryMasterController(productCategoryMaster);
        mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
    }

    @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"));
    }
}

方案选择

  • 方案一适合需要验证Web层完整配置(如拦截器、消息转换器)的场景,测试更贴近真实运行环境。
  • 方案二运行速度更快,适合快速验证Controller的业务逻辑,无需依赖Spring上下文。

内容的提问来源于stack exchange,提问作者Art yudi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 05:15:55