在正常單元測試中,我們向方法上添加@Test注解即可,但是在springboot中我們要使用類似控制器注入方法
@Autowired
userService userService;
又或者注入Dao層方法
@Autowired
private YiSouMapper yiSouMapper;
這種自動裝配的類就可能會注入失敗,報空指針異常,就是userService或yiSouMapper無法被注入,
那么springboot就給了我們一個將junit與springboot結合起來的依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
導入這個依賴以后我們在我們的測試類上添加@RunWith和@SpringBootTest兩個注解,記住@SpringBootTes中的classes就是你自己springboot的啟動類,
名字需要換一下。這時運行后會啟動項目環境,使用當前Spring環境進行單元測試。
@RunWith(SpringRunner.class)
@SpringBootTest(classes = EdApplication.class)
public class FenCiUtilText {
@Autowired
private YiSouMapper yiSouMapper;
@Test
public void testDemo1() {
//代碼
}
}
