快速文档中使用的测试类是这样的
@SpringBootTest
public class SampleTest {
@Autowired
private UserMapper userMapper;
@Test
public void testSelect() {
System.out.println(("----- selectAll method test ------"));
List<User> userList = userMapper.selectList(null);
Assert.assertEquals(5, userList.size());
userList.forEach(System.out::println);
}
}
运行测试类就会报空指针异常,UserMapper 没有被注入成功
java.lang.NullPointerException at test.SampleTest.testSelect(SampleTest.java:21)
解决办法:
在测试类上添加上 @RunWith(SpringRunner.class) 它的作用:
在正常情况下测试类是需要@RunWith的,作用是告诉java你这个类通过什么运行环境运行,例如启动和创建spring的应用上下文。
但是只添加这个还不够,还是会 报错,异常信息中提示需要指定启动类。
IllegalStateException: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test
最终能运行的测试类