Junit這種老技術,現在又拿出來說,不為別的,某種程度上來說,更是為了要說明它在項目中的重要性。
憑本人的感覺和經驗來說,在項目中完全按標準都寫Junit用例覆蓋大部分業務代碼的,應該不會超過一半。
剛好前段時間寫了一些關于SpringBoot的帖子,正好現在把Junit再拿出來從幾個方面再說一下,也算是給一些新手參考了。
那么先簡單說一下為什么要寫測試用例
1. 可以避免測試點的遺漏,為了更好的進行測試,可以提高測試效率
2. 可以自動測試,可以在項目打包前進行測試校驗
3. 可以及時發現因為修改代碼導致新的問題的出現,并及時解決
那么本文從以下幾點來說明怎么使用Junit,Junit4比3要方便很多,細節大家可以自己了解下,主要就是版本4中對方法命名格式不再有要求,不再需要繼承TestCase,一切都基于注解實現。
1、SpringBoot Web項目中中如何使用Junit
創建一個普通的Java類,在Junit4中不再需要繼承TestCase類了。
因為我們是Web項目,所以在創建的Java類中添加注解:
1
2
3
|
@RunWith (SpringJUnit4ClassRunner. class ) // SpringJUnit支持,由此引入Spring-Test框架支持! @SpringApplicationConfiguration (classes = SpringBootSampleApplication. class ) // 指定我們SpringBoot工程的Application啟動類 @WebAppConfiguration // 由于是Web項目,Junit需要模擬ServletContext,因此我們需要給我們的測試類加上@WebAppConfiguration。 |
接下來就可以編寫測試方法了,測試方法使用@Test注解標注即可。
在該類中我們可以像平常開發一樣,直接@Autowired來注入我們要測試的類實例。
下面是完整代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
|
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); } } |
接下來,你需要新增無數個測試類,編寫無數個測試方法來保障我們開發完的程序的有效性。
2、Junit基本注解介紹
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
//在所有測試方法前執行一次,一般在其中寫上整體初始化的代碼 @BeforeClass //在所有測試方法后執行一次,一般在其中寫上銷毀和釋放資源的代碼 @AfterClass //在每個測試方法前執行,一般用來初始化方法(比如我們在測試別的方法時,類中與其他測試方法共享的值已經被改變,為了保證測試結果的有效性,我們會在@Before注解的方法中重置數據) @Before //在每個測試方法后執行,在方法執行完成后要做的事情 @After // 測試方法執行超過1000毫秒后算超時,測試將失敗 @Test (timeout = 1000 ) // 測試方法期望得到的異常類,如果方法執行沒有拋出指定的異常,則測試失敗 @Test (expected = Exception. class ) // 執行測試時將忽略掉此方法,如果用于修飾類,則忽略整個類 @Ignore (“not ready yet”) @Test @RunWith |
在JUnit中有很多個Runner,他們負責調用你的測試代碼,每一個Runner都有各自的特殊功能,你要根據需要選擇不同的Runner來運行你的測試代碼。
如果我們只是簡單的做普通Java測試,不涉及spring Web項目,你可以省略@RunWith注解,這樣系統會自動使用默認Runner來運行你的代碼。
3、參數化測試
Junit為我們提供的參數化測試需要使用 @RunWith(Parameterized.class)
然而因為Junit 使用@RunWith指定一個Runner,在我們更多情況下需要使用@RunWith(SpringJUnit4ClassRunner.class)來測試我們的Spring工程方法,所以我們使用assertArrayEquals 來對方法進行多種可能性測試便可。
下面是關于參數化測試的一個簡單例子:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
|
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; /** * 該構造方法的參數與下面@Parameters注解的方法中的Object數組中值的順序對應 * @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 數組中值的順序注意要和上面的構造方法ParameterTest的參數對應 return Arrays.asList( new Object[][]{ { "小明2" , true }, { "壞" , false }, { "莉莉" , false }, }); } } |
4、打包測試
正常情況下我們寫了5個測試類,我們需要一個一個執行。
打包測試,就是新增一個類,然后將我們寫好的其他測試類配置在一起,然后直接運行這個類就達到同時運行其他幾個測試的目的。
代碼如下:
1
2
3
4
5
|
@RunWith (Suite. class ) @SuiteClasses ({ATest. class , BTest. class , CTest. class }) public class ABCSuite { // 類中不需要編寫代碼 } |
5、使用Junit測試HTTP的API接口
我們可以直接使用這個來測試我們的Rest API,如果內部單元測試要求不是很嚴格,我們保證對外的API進行完全測試即可,因為API會調用內部的很多方法,姑且把它當做是整合測試吧。
下面是一個簡單的例子:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
|
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表示端口號隨機,也可以具體指定如8888這樣的固定端口 public class HelloControllerTest { private String dateReg; private Pattern pattern; private RestTemplate template = new TestRestTemplate(); @Value ( "${local.server.port}" ) // 注入端口號 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 來捕獲指定方法開始執行以后的所有輸出,包括System.out輸出和Log日志。
OutputCapture 需要使用@Rule注解,并且實例化的對象需要使用public修飾,如下代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
@RunWith (SpringJUnit4ClassRunner. class ) @SpringApplicationConfiguration (classes = SpringBootSampleApplication. class ) //@WebAppConfiguration // 使用@WebIntegrationTest注解需要將@WebAppConfiguration注釋掉 @WebIntegrationTest ( "server.port:0" ) // 使用0表示端口號隨機,也可以具體指定如8888這樣的固定端口 public class HelloControllerTest { @Value ( "${local.server.port}" ) // 注入端口號 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日志也會被capture捕獲測試輸出" ); assertThat(capture.toString(), Matchers.containsString( "World" )); } } |
關于Assert類中的一些斷言方法,都很簡單,本文不再贅述。
但是在新版的Junit中,assertEquals 方法已經被廢棄,它建議我們使用assertArrayEquals,旨在讓我們測試一個方法的時候多傳幾種參數進行多種可能性測試。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:http://blog.csdn.net/catoop/article/details/50752964