(二)搭建測(cè)試環(huán)境

Spring Boot Test 簡(jiǎn)介

Spring Boot提供了大量的實(shí)用的注解來(lái)幫助我們測(cè)試程序。針對(duì)測(cè)試支持由兩個(gè)模塊提供,spring-boot-test包含核心項(xiàng)目,而spring-boot-test-autoconfigure支持測(cè)試的自動(dòng)配置。

大多數(shù)開(kāi)發(fā)人員只使用spring-boot-starter-test即可,它會(huì)導(dǎo)入兩個(gè)Spring Boot測(cè)試模塊以及JUnit,AssertJ,Hamcrest和一些其他有用的庫(kù)。

搭建測(cè)試環(huán)境

? 基于上文中的例子,我們來(lái)搭建測(cè)試環(huán)境。

1、在pom.xml文件中,添加spring-boot-starter-test的依賴,它包含了一系列的測(cè)試庫(kù)(JUnit?、Spring Test 、AssertJ?、Hamcrest、Mockito?、JSONassert?、JsonPath?)。

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

2、我們簡(jiǎn)單的先針對(duì)Controller層進(jìn)行單元測(cè)試。測(cè)試Spring MVC只需在對(duì)應(yīng)的測(cè)試類上添加@WebMvcTest注解即可。由于是基于Spring Test環(huán)境下的單元測(cè)試,請(qǐng)不要忘記添加@RunWith(SpringRunner.class)注解。

test\java\com\jason\web目錄下新建IndexControllerTest.java文件。

package com.jason.web;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@RunWith(SpringRunner.class)
@WebMvcTest(IndexController.class)
public class IndexControllerTest {

    @Autowired
    private MockMvc mvc;

    @Test
    public void testIndex() throws Exception {
        this.mvc.perform(get("/index").accept(MediaType.TEXT_PLAIN))
                .andExpect(status().isOk()).andExpect(content().string("Hello, Spring Boot!"));
    }

}

3、運(yùn)行IndexControllerTest.java中的testIndex()方法,即可看到測(cè)試結(jié)果。

本文示例程序請(qǐng)點(diǎn)此獲取。
詳細(xì)資料請(qǐng)參考Spring Boot官網(wǎng)。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開(kāi)發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,554評(píng)論 19 139
  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 47,273評(píng)論 6 342
  • 此篇翻譯的是Spring Boot官方指南 Part III. 使用 Spring Boot (Using Spr...
    K天道酬勤閱讀 6,947評(píng)論 0 21
  • Spring 技術(shù)筆記Day 1 預(yù)熱知識(shí)一、 基本術(shù)語(yǔ)Blob類型,二進(jìn)制對(duì)象Object Graph:對(duì)象圖...
    OchardBird閱讀 1,078評(píng)論 0 2
  • 最近,總覺(jué)得自己閱讀能力在逐漸喪失,算是件可怕的事情,目前一起看的兩本書是《不安之書》和《親愛(ài)的生活》。 先說(shuō)說(shuō)前...
    大蔥拌咖啡閱讀 485評(píng)論 0 0

友情鏈接更多精彩內(nèi)容