问题:
因为项目使用了微服务,所以为了图省事在微服务中创建了一个服务写Mybatis Plus,但是根据官网文档写完再Junit测试的时候出现了空指针错误。
官网文档的测试类:
出现错误:
发现userMapper的值为空
通过查资料发现这是因为普通类不能使用SpringBean,所以普通的测试类是无法获取bean的,所以才会报空指针。因此我们需要让这个测试类能获取到bean。
解决方法:
添加测试依赖:
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
并且在测试类上增加注解:
@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
解决问题