首页 > 解决方案 > api测试期间的SpringBoot Nullpointer异常

问题描述

我正在尝试为我的休息控制器编写测试,并NullPointerException在我尝试对MockMvc实例执行操作时得到一个。

我的项目结构如下:

POJO:

@Entity
public class Pair {
    @Id
    @JsonIgnore
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String a;
    private String b;

    //getters and setters...

}

休息控制器:

@RestController
public class PairController {

    @Autowired
    private PairServiceImpl pairService;

    @RequestMapping(value = "/pair", method = RequestMethod.POST)
    public Pair addPair(String a, String b) {
        Pair newPair = new Pair();
        newPair.setA(a);
        newPair.setB(b);
        return pairService.addNewPair(newPair);
    }

    @RequestMapping(value = "/pair", method = RequestMethod.GET)
    public List<Pair> getPairs() {
        return pairService.getPairs();
    }
}

服务层:

@Service
public class PairServiceImpl implements PairService {
    @Autowired 
    private PairRepositoryImpl pairRepository;

    public Pair addNewPair(Pair newPair) {
        return pairRepository.save(newPair);
    }

    public List<Pair> getPairs() {
        return pairRepository.findAll();
    }
}

存储库:

public interface PairRepositoryImpl extends JpaRepository<Pair, Long> {

}

我想测试 PairController API 端点:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {DemoApplication.class, DatabaseConfig.class})
@AutoConfigureMockMvc
@ContextConfiguration(classes = {PairController.class})
public class PairControllerTests {

    @Autowired
    private MockMvc mockMvc;

    @Autowired
    private PairService pairService;

    @Test
    public void addPairTest() {
        Pair testPair = new Pair();
        testPair.setA("a");
        testPair.setB("b");
        ObjectMapper objectMapper = new ObjectMapper();

        MvcResult mvcResult =      mockMvc.perform(MockMvcRequestBuilders.post("/pair").accept(MediaType.APPLICATION_JSON)
            .content(objectMapper.writeValueAsString(testPair))).andReturn();
        //The line above throws an exception
        int status = mvcResult.getResponse().getStatus();
        assertEquals(200, status);
    }
}

如果我不添加@ContextConfiguration测试无法找到我的端点。我试图在addPair调用该方法时记录 a 和 b 值,并且两个值都是null. 您还可以看到我添加了一个自定义数据库配置类“ DatabaseConfig”,其中包含一个 H2 嵌入式数据库数据源方法,因此测试不使用生产数据库。@EnableJpaRepositories注释存在于此类中,它指向上面显示的存储库。

我试图处理许多不同的注释,但它们都有相同的最终结果:控制器方法中的 null 值。

我还尝试MockMvc使用 WebApplicationContext 手动构造实例,并使用它在带有注释的方法@Autowired中初始化实例- 但最终结果是相同的。MockMvc@Before

我在类中引发异常的行下方发表了评论PairControllerTests

因此,如果我运行该应用程序并使用 Postman 和生产数据库对其进行测试,则端点可以正常工作,并且可以正确保存和检索数据。此问题仅在测试期间发生。

标签: javaspringspring-bootspring-test

解决方案


推荐阅读