springboot使用測試類報空指針異常
之前在用springboot做增刪改查時想測試是否能順利連接數據庫並取值。
但只要一加上test注解並做測試,屢屢報空,百思不得其解。
最后終於找到原因,將這個浪費很多時間的不算知識點的知識點記錄一下。
首先檢查依賴有無問題
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
之后,檢查語句,找過mapper接口和mapper.xml的原因,找過service接口的原因,甚至還找過數據庫的。
浪費了很多時間之后向百度求饒。
@RunWith(SpringRunner.class)
@SpringBootTest
public class Test {
@Resource
SelectService selectService;
@org.junit.Test
public void query(){
List<City1> query = selectService.queryById(1001);
query.forEach(city1 -> System.out.println(city1));
}
}
springboot使用 test,需要添加兩個注解@RunWith和@SpringBootTest。而@RunWith需要引用SpringRunner類。
關於這幾個注解的釋義有很多,就不多說了,互聯網上有很多。