单元测试遇到的问题总结

1.启动出现空指针异常

问题:少加了注解

原因分析:
测试类没有扫描到service层,导致userService注入失败,调用userService对应的方法的时候自然会报NullPointerException
在测试类上面加上@SpringBootTest()和@RunWith(SpringRunner.class)注解即可

2.启动还是报错

问题:springcloud的版本和springboot的版本没对应上

成功案例:

@RunWith(SpringRunner.class)
@SpringBootTest()
public class GulimallProductApplicationTests {

    @Autowired
    private BrandService brandService;

    @Test
    public void contextLoads() {
        BrandEntity brandEntity = new BrandEntity();
        brandEntity.setName("华为");
        brandService.save(brandEntity);
        System.out.println("保存成功!");
    }

}

 

posted @ 2021-12-17 15:21  迷糊桃  阅读(206)  评论(0编辑  收藏  举报