Springboot_13_單元測試

http://412887952-qq-com.iteye.com/blog/2317832-Junit1.4版本

添加依賴

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

測試Service

@Service
public class StudentService{
    @Resource
    private StudentDao studentDao;

    public String junitTest(){
        return "hello";
    }
}

測試

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.tutorial.springboot.AppStart;
import com.tutorial.springboot.service.StudentService;

//SpringJUnit支持,由此引入Spring-Test框架支持
@RunWith(SpringJUnit4ClassRunner.class)
//指定我們SpringBoot工程的Application啟動類
@SpringApplicationConfiguration(classes = AppStart.class)
//1.4.0已經被標注過時,需要替換為@SpringbootTest注解
//由于是Web項目,Junit需要模擬ServletContext,因此我們需要給我們的測試類加上@WebAppConfiguration
@WebAppConfiguration
public class SpringBootTest{
    @Resource
    private StudentService studentService;

    @Test
    public void testGetName(){
           Assert.assertEquals("hello",studentService.junitTest());
    }
}

Junit基本注解介紹

//在所有測試方法前執(zhí)行一次,一般在其中寫上整體初始化的代碼 @BeforeClass
//在所有測試方法后執(zhí)行一次,一般在其中寫上銷毀和釋放資源的代碼 @AfterClass
//在每個測試方法前執(zhí)行,一般用來初始化方法(比如我們在測試別的方法時,類中與其他測試方法共享的值已經被改變,為了保證測試結果的有效性,我們會在@Before注解的方法中重置數據) @Before
//在每個測試方法后執(zhí)行,在方法執(zhí)行完成后要做的事情 @After
// 測試方法執(zhí)行超過1000毫秒后算超時,測試將失敗 @Test(timeout = 1000)
// 測試方法期望得到的異常類,如果方法執(zhí)行沒有拋出指定的異常,則測試失敗 @Test(expected = Exception.class)
// 執(zhí)行測試時將忽略掉此方法,如果用于修飾類,則忽略整個類 @Ignore(“not ready yet”) @Test
@RunWith 在JUnit中有很多個Runner,他們負責調用你的測試代碼,每一個Runner都有各自的特殊功能,你要根據需要選擇不同的Runner來運行你的測試代碼。 如果我們只是簡單的做普通Java測試,不涉及SpringWeb項目,你可以省略@RunWith注解,這樣系統(tǒng)會自動使用默認Runner來運行你的代碼。
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

  • 使用SpringMVC來實現一組對User對象操作的RESTful API,配合注釋詳細說明在Spring MVC...
    perfect_jimmy閱讀 585評論 0 0
  • Spring Cloud為開發(fā)人員提供了快速構建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務發(fā)現,斷路器,智...
    卡卡羅2017閱讀 136,506評論 19 139
  • Spring Boot 參考指南 介紹 轉載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 47,256評論 6 342
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 178,816評論 25 709
  • 木子李 遇見檸檬 檸檬,沒有棠梨胭脂色,沒有蕎麥白雪香 但是,它是不一樣的黃,不一樣的青 是黃得耀眼,青得樂觀 經...
    芷木槿閱讀 174評論 0 1

友情鏈接更多精彩內容