我的单元测试收到错误 java.lang.AssertionError: JSON path "$.id" Expected:<1> but was:<9> 但是当我使用邮递员测试时一切都很顺利
@SpringBootTest
@ExtendWith(MockitoExtension.class)
@AutoConfigureMockMvc
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"));
}
我添加了objectMapper、@SpringBootTest和@AutoConfigureMockMvc的配置类
@org.springframework.boot.test.context.TestConfiguration
public class TestConfiguration {
@Bean
public ObjectMapper objectMapper() {
// Customize and configure the ObjectMapper as needed
return new ObjectMapper();
}
}
任何人都可以帮我修改我的代码吗?
objectMapper
从未初始化。您需要将 objectMapper
实例化为 new ObjectMapper
,然后您就可以调用它的方法。虽然它没有正确初始化,但它的值为 null
,即未知/未定义/nil,并且您无法调用 null
的方法。