1. 程式人生 > >(27)Spring Boot Junit單元測試【從零開始學Spring Boot】

(27)Spring Boot Junit單元測試【從零開始學Spring Boot】

Junit這種老技術,現在又拿出來說,不為別的,某種程度上來說,更是為了要說明它在專案中的重要性。

那麼先簡單說一下為什麼要寫測試用例
1. 
可以避免測試點的遺漏,為了更好的進行測試,可以提高測試效率
2. 
可以自動測試,可以在專案打包前進行測試校驗
3. 
可以及時發現因為修改程式碼導致新的問題的出現,並及時解決

那麼本文從以下幾點來說明怎麼使用JunitJunit43要方便很多,細節大家可以自己瞭解下,主要就是版本4中對方法命名格式不再有要求,不再需要繼承TestCase,一切都基於註解實現。

那麼Spring Boot如何使用Junit呢?

      1). 加入Maven的依賴;

      2). 編寫測試

service;

      3). 編寫測試類;

1). 加入Maven的依賴:

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
</dependency>

2). 編寫測試service:

新建com.kfit.service.HelloService 提供測試方法:

package com.kfit.service;

import org.springframework.stereotype.Service;

@Service

publicclass HelloService {

    public String getName(){

       return"hello";

    }

}

3). 編寫測試類:

src/test/java下編寫測試類:com.kfit.test.HelloServiceTest:

package com.kfit.test;

import javax.annotation.Resource;

import

 org.junit.Assert;

import org.junit.Test;

import org.junit.runner.RunWith;

import org.springframework.boot.test.SpringApplicationConfiguration;

import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import org.springframework.test.context.web.WebAppConfiguration;

import com.kfit.App;

import com.kfit.service.HelloService;

//// SpringJUnit支援,由此引入Spring-Test框架支援!

@RunWith(SpringJUnit4ClassRunner.class)

//// 指定我們SpringBoot工程的Application啟動類

@SpringApplicationConfiguration(classes = App.class)

///由於是Web專案,Junit需要模擬ServletContext,因此我們需要給我們的測試類加上@WebAppConfiguration

@WebAppConfiguration

publicclass HelloServiceTest {

    @Resource

    private HelloService helloService;

    @Test

    publicvoid testGetName(){

       Assert.assertEquals("hello",helloService.getName());

    }

}

這時候就可以進行測試了,右鍵—Run As – Junit Test

Junit基本註解介紹

//在所有測試方法前執行一次,一般在其中寫上整體初始化的程式碼 
@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來執行你的程式碼。