詳解Spring Boot Junit單元測(cè)試
Junit這種老技術(shù),現(xiàn)在又拿出來說,不為別的,某種程度上來說,更是為了要說明它在項(xiàng)目中的重要性。
憑本人的感覺和經(jīng)驗(yàn)來說,在項(xiàng)目中完全按標(biāo)準(zhǔn)都寫Junit用例覆蓋大部分業(yè)務(wù)代碼的,應(yīng)該不會(huì)超過一半。
剛好前段時(shí)間寫了一些關(guān)于SpringBoot的帖子,正好現(xiàn)在把Junit再拿出來從幾個(gè)方面再說一下,也算是給一些新手參考了。
那么先簡(jiǎn)單說一下為什么要寫測(cè)試用例
1. 可以避免測(cè)試點(diǎn)的遺漏,為了更好的進(jìn)行測(cè)試,可以提高測(cè)試效率
2. 可以自動(dòng)測(cè)試,可以在項(xiàng)目打包前進(jìn)行測(cè)試校驗(yàn)
3. 可以及時(shí)發(fā)現(xiàn)因?yàn)樾薷拇a導(dǎo)致新的問題的出現(xiàn),并及時(shí)解決
那么本文從以下幾點(diǎn)來說明怎么使用Junit,Junit4比3要方便很多,細(xì)節(jié)大家可以自己了解下,主要就是版本4中對(duì)方法命名格式不再有要求,不再需要繼承TestCase,一切都基于注解實(shí)現(xiàn)。
1、SpringBoot Web項(xiàng)目中中如何使用Junit
創(chuàng)建一個(gè)普通的Java類,在Junit4中不再需要繼承TestCase類了。
因?yàn)槲覀兪荳eb項(xiàng)目,所以在創(chuàng)建的Java類中添加注解:
@RunWith(SpringJUnit4ClassRunner.class) // SpringJUnit支持,由此引入Spring-Test框架支持! @SpringApplicationConfiguration(classes = SpringBootSampleApplication.class) // 指定我們SpringBoot工程的Application啟動(dòng)類 @WebAppConfiguration // 由于是Web項(xiàng)目,Junit需要模擬ServletContext,因此我們需要給我們的測(cè)試類加上@WebAppConfiguration。
接下來就可以編寫測(cè)試方法了,測(cè)試方法使用@Test注解標(biāo)注即可。
在該類中我們可以像平常開發(fā)一樣,直接@Autowired來注入我們要測(cè)試的類實(shí)例。
下面是完整代碼:
package org.springboot.sample;
import static org.junit.Assert.assertArrayEquals;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springboot.sample.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
/**
*
* @author 單紅宇(365384722)
* @create 2016年2月23日
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = SpringBootSampleApplication.class)
@WebAppConfiguration
public class StudentTest {
@Autowired
private StudentService studentService;
@Test
public void likeName() {
assertArrayEquals(
new Object[]{
studentService.likeName("小明2").size() > 0,
studentService.likeName("壞").size() > 0,
studentService.likeName("莉莉").size() > 0
},
new Object[]{
true,
false,
true
}
);
// assertTrue(studentService.likeName("小明2").size() > 0);
}
}
接下來,你需要新增無數(shù)個(gè)測(cè)試類,編寫無數(shù)個(gè)測(cè)試方法來保障我們開發(fā)完的程序的有效性。
2、Junit基本注解介紹
//在所有測(cè)試方法前執(zhí)行一次,一般在其中寫上整體初始化的代碼 @BeforeClass //在所有測(cè)試方法后執(zhí)行一次,一般在其中寫上銷毀和釋放資源的代碼 @AfterClass //在每個(gè)測(cè)試方法前執(zhí)行,一般用來初始化方法(比如我們?cè)跍y(cè)試別的方法時(shí),類中與其他測(cè)試方法共享的值已經(jīng)被改變,為了保證測(cè)試結(jié)果的有效性,我們會(huì)在@Before注解的方法中重置數(shù)據(jù)) @Before //在每個(gè)測(cè)試方法后執(zhí)行,在方法執(zhí)行完成后要做的事情 @After // 測(cè)試方法執(zhí)行超過1000毫秒后算超時(shí),測(cè)試將失敗 @Test(timeout = 1000) // 測(cè)試方法期望得到的異常類,如果方法執(zhí)行沒有拋出指定的異常,則測(cè)試失敗 @Test(expected = Exception.class) // 執(zhí)行測(cè)試時(shí)將忽略掉此方法,如果用于修飾類,則忽略整個(gè)類 @Ignore(“not ready yet”) @Test @RunWith
在JUnit中有很多個(gè)Runner,他們負(fù)責(zé)調(diào)用你的測(cè)試代碼,每一個(gè)Runner都有各自的特殊功能,你要根據(jù)需要選擇不同的Runner來運(yùn)行你的測(cè)試代碼。
如果我們只是簡(jiǎn)單的做普通Java測(cè)試,不涉及spring Web項(xiàng)目,你可以省略@RunWith注解,這樣系統(tǒng)會(huì)自動(dòng)使用默認(rèn)Runner來運(yùn)行你的代碼。
3、參數(shù)化測(cè)試
Junit為我們提供的參數(shù)化測(cè)試需要使用 @RunWith(Parameterized.class)
然而因?yàn)镴unit 使用@RunWith指定一個(gè)Runner,在我們更多情況下需要使用@RunWith(SpringJUnit4ClassRunner.class)來測(cè)試我們的Spring工程方法,所以我們使用assertArrayEquals 來對(duì)方法進(jìn)行多種可能性測(cè)試便可。
下面是關(guān)于參數(shù)化測(cè)試的一個(gè)簡(jiǎn)單例子:
package org.springboot.sample;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.Collection;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
@RunWith(Parameterized.class)
public class ParameterTest {
private String name;
private boolean result;
/**
* 該構(gòu)造方法的參數(shù)與下面@Parameters注解的方法中的Object數(shù)組中值的順序?qū)?yīng)
* @param name
* @param result
*/
public ParameterTest(String name, boolean result) {
super();
this.name = name;
this.result = result;
}
@Test
public void test() {
assertTrue(name.contains("小") == result);
}
/**
* 該方法返回Collection
*
* @return
* @author SHANHY
* @create 2016年2月26日
*/
@Parameters
public static Collection<?> data(){
// Object 數(shù)組中值的順序注意要和上面的構(gòu)造方法ParameterTest的參數(shù)對(duì)應(yīng)
return Arrays.asList(new Object[][]{
{"小明2", true},
{"壞", false},
{"莉莉", false},
});
}
}
4、打包測(cè)試
正常情況下我們寫了5個(gè)測(cè)試類,我們需要一個(gè)一個(gè)執(zhí)行。
打包測(cè)試,就是新增一個(gè)類,然后將我們寫好的其他測(cè)試類配置在一起,然后直接運(yùn)行這個(gè)類就達(dá)到同時(shí)運(yùn)行其他幾個(gè)測(cè)試的目的。
代碼如下:
@RunWith(Suite.class)
@SuiteClasses({ATest.class, BTest.class, CTest.class})
public class ABCSuite {
// 類中不需要編寫代碼
}
5、使用Junit測(cè)試HTTP的API接口
我們可以直接使用這個(gè)來測(cè)試我們的Rest API,如果內(nèi)部單元測(cè)試要求不是很嚴(yán)格,我們保證對(duì)外的API進(jìn)行完全測(cè)試即可,因?yàn)锳PI會(huì)調(diào)用內(nèi)部的很多方法,姑且把它當(dāng)做是整合測(cè)試吧。
下面是一個(gè)簡(jiǎn)單的例子:
package org.springboot.sample;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.hamcrest.Matchers;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.TestRestTemplate;
import org.springframework.boot.test.WebIntegrationTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
/**
*
* @author 單紅宇(365384722)
* @create 2016年2月23日
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = SpringBootSampleApplication.class)
//@WebAppConfiguration // 使用@WebIntegrationTest注解需要將@WebAppConfiguration注釋掉
@WebIntegrationTest("server.port:0")// 使用0表示端口號(hào)隨機(jī),也可以具體指定如8888這樣的固定端口
public class HelloControllerTest {
private String dateReg;
private Pattern pattern;
private RestTemplate template = new TestRestTemplate();
@Value("${local.server.port}")// 注入端口號(hào)
private int port;
@Test
public void test3(){
String url = "http://localhost:"+port+"/myspringboot/hello/info";
MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>();
map.add("name", "Tom");
map.add("name1", "Lily");
String result = template.postForObject(url, map, String.class);
System.out.println(result);
assertNotNull(result);
assertThat(result, Matchers.containsString("Tom"));
}
}
6、捕獲輸出
使用 OutputCapture 來捕獲指定方法開始執(zhí)行以后的所有輸出,包括System.out輸出和Log日志。
OutputCapture 需要使用@Rule注解,并且實(shí)例化的對(duì)象需要使用public修飾,如下代碼:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = SpringBootSampleApplication.class)
//@WebAppConfiguration // 使用@WebIntegrationTest注解需要將@WebAppConfiguration注釋掉
@WebIntegrationTest("server.port:0")// 使用0表示端口號(hào)隨機(jī),也可以具體指定如8888這樣的固定端口
public class HelloControllerTest {
@Value("${local.server.port}")// 注入端口號(hào)
private int port;
private static final Logger logger = LoggerFactory.getLogger(StudentController.class);
@Rule
// 這里注意,使用@Rule注解必須要用public
public OutputCapture capture = new OutputCapture();
@Test
public void test4(){
System.out.println("HelloWorld");
logger.info("logo日志也會(huì)被capture捕獲測(cè)試輸出");
assertThat(capture.toString(), Matchers.containsString("World"));
}
}
關(guān)于Assert類中的一些斷言方法,都很簡(jiǎn)單,本文不再贅述。
但是在新版的Junit中,assertEquals 方法已經(jīng)被廢棄,它建議我們使用assertArrayEquals,旨在讓我們測(cè)試一個(gè)方法的時(shí)候多傳幾種參數(shù)進(jìn)行多種可能性測(cè)試。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Java根據(jù)URL下載文件到本地的2種方式(大型文件與小型文件)
這篇文章主要給大家介紹了關(guān)于Java根據(jù)URL下載文件到本地的2種方式,分別是大型文件與小型文件,避免內(nèi)存溢出OOM,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下2024-01-01
關(guān)于idea一直卡在build不動(dòng)的解決方案
這篇文章主要介紹了idea一直卡在build不動(dòng)的解決方案,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-10-10
關(guān)于Java JDK安裝、配置環(huán)境變量的問題
這篇文章主要介紹了Java JDK安裝、配置環(huán)境變量,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-03-03
java根據(jù)圖片中綠色像素點(diǎn)的多少進(jìn)行排序
這篇文章主要介紹了java根據(jù)圖片中綠色像素點(diǎn)的多少進(jìn)行排序,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-03-03
關(guān)于在Java中如何使用yaml的實(shí)例
這篇文章主要介紹了關(guān)于在Java中如何使用yaml的實(shí)例,YAML是一種輕量級(jí)的數(shù)據(jù)序列化格式。它以易讀、易寫的文本格式表示數(shù)據(jù),支持列表、字典等各種數(shù)據(jù)結(jié)構(gòu),被廣泛應(yīng)用于配置文件、數(shù)據(jù)傳輸協(xié)議等領(lǐng)域,需要的朋友可以參考下2023-08-08

