前言
junit用于單元測試。
操作步驟
-
新建springboot項目(不依賴任何插件,所以不需要選擇任何插件)
-
引入test依賴(新建項目自動引入了這個依賴,如果沒有這個依賴,才需要添加)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
高版本的springboot(例如:2.6.5)只有junit5沒有引入junit4,所以需要導(dǎo)入依賴(如果出現(xiàn)import灰色時,請檢查是不是需要導(dǎo)入junit4),但是低版本springboot(例如:2.1.8.RELEASE)的已經(jīng)引入了junit4,所以不需要引入。
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
- 新建service和實現(xiàn)
HelloService.java
package com.it2.springbootjunit.service;
import org.springframework.stereotype.Service;
public interface HelloService {
void hello();
}
@Service
class HelloServiceImpl implements HelloService{
@Override
public void hello() {
System.out.println("hello world");
}
}
- 創(chuàng)建測試用例
HelloServiceTest.java
package com.it2;
import com.it2.springbootjunit.SpringbootJunit01Application;
import com.it2.springbootjunit.service.HelloService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
//設(shè)置引導(dǎo)類SpringbootJunit01Application
@SpringBootTest(classes = SpringbootJunit01Application.class)
public class HelloServiceTest {
@Autowired
private HelloService helloService;
@Test
public void hello(){
helloService.hello();
}
}
- 運行測試
不需要設(shè)置引導(dǎo)類
如果測試類與引入類 (@Autowired)是同名包,或者測試類是引入類的子包,則不需要聲明引導(dǎo)類,也可以運行。
下面這個是反例:測試類不是引入類的同名包,也不是其子包,執(zhí)行報錯(提示你的測試需要添加引導(dǎo)類)。(注意:編譯語法檢查報錯不代表程序一定運行不通過)文章來源:http://www.zghlxwxcb.cn/news/detail-426015.html
@RunWith(SpringRunner.class)
如果添加@RunWith(SpringRunner.class),則會啟動springboot,加載容器,運行會比較慢。
如果測試用例不需要用到可以取消。
下面的demo直觀的顯示了@RunWith(SpringRunner.class)的區(qū)別,如果測試用例未使用到容器里的bean,則不需要該注解。如果使用到了容器的bean,則需要使用該注解。下圖中,顯然當使用@RunWith(SpringRunner.class)會很慢。文章來源地址http://www.zghlxwxcb.cn/news/detail-426015.html
到了這里,關(guān)于springboot框架(2):整合junit4的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!