SpringBoot 測(cè)試

Mac下idea的使用之常用快捷鍵篇

@Controller 父虑、@RestController单山、@Service@Repository 悠砚、@Component
RestController和Controller的區(qū)別

一晓勇、SpringBoot 網(wǎng)絡(luò)接口測(cè)試

接口類:HelloController

package com.lonelyflow.dcoker.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
public class HelloController {
    @RequestMapping("/hello")
    public Map<String,Object> hello(Map<String,Object> params){
        Map<String,Object> result = new HashMap<String, Object>();
        result.put("name","hello");
        result.put("nickname","獨(dú)孤九劍");
        return  result;
    }
}

測(cè)試類HelloControllerbTests

package com.lonelyflow.dcoker.Controller;

import com.lonelyflow.dcoker.controller.HelloController;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@RunWith(SpringRunner.class)
@SpringBootTest
public class HelloControllerbTests {
    /**
    @Test,把一個(gè)方法標(biāo)記為測(cè)試方法
    @Before灌旧,每一個(gè)測(cè)試方法執(zhí)行前自動(dòng)調(diào)用一次
    @After绑咱,每一個(gè)測(cè)試方法執(zhí)行完自動(dòng)調(diào)用一次
    @BeforeClass,所有測(cè)試方法執(zhí)行前執(zhí)行一次枢泰,在測(cè)試類還沒有實(shí)例化就已經(jīng)被加載描融,因此用 static 修飾
    @AfterClass,所有測(cè)試方法執(zhí)行前執(zhí)行一次衡蚂,在測(cè)試類還沒有實(shí)例化就已經(jīng)被加載窿克,因此用 static 修飾
    @Ignore,暫不執(zhí)行該測(cè)試方法
    @RunWith 當(dāng)一個(gè)類用 @RunWith 注釋或繼承一個(gè)用 @RunWith 注釋的類時(shí)毛甲,
    JUnit 將調(diào)用它所引用的類來運(yùn)行該類中的測(cè)試而不是開發(fā)者再去 JUnit 內(nèi)部去構(gòu)建它年叮。我們?cè)陂_發(fā)過程中使用這個(gè)特性看看。
    */
    // 用于模擬網(wǎng)絡(luò)請(qǐng)求的測(cè)試
    private MockMvc mockMvc;

    @Before
    public void setUp() throws Exception {
        mockMvc = MockMvcBuilders.standaloneSetup(new HelloController()).build();
    }
    /**
     * 模擬網(wǎng)絡(luò)的請(qǐng)求及打印
     */
    @Test
    public void getHelloWeb() throws Exception {
//        // 發(fā)送請(qǐng)求并接收數(shù)據(jù)玻募,然后打印消息
//        mockMvc.perform(
//                MockMvcRequestBuilders.post("/hello?name=小明")
//                        .accept(MediaType.APPLICATION_JSON_UTF8)
//        ).andDo(print());
//
//        // 模擬多參數(shù)
//        mockMvc.perform(
//                MockMvcRequestBuilders.post("/saveUser")
//                        .param("name","")
//                        .param("age","666")
//                        .param("pass","test")
//                        .accept(MediaType.APPLICATION_JSON_UTF8)
//        ).andDo(print());

        /**
         * perform 構(gòu)建一個(gè)請(qǐng)求只损,并且返回 ResultActions 實(shí)例,該實(shí)例則可以獲取到請(qǐng)求的返回內(nèi)容七咧。
         * params 構(gòu)建請(qǐng)求時(shí)候的參數(shù)改执,也支持 param(key,value) 的方式連續(xù)添加。
         * contentType(MediaType.APPLICATION_JSON_UTF8) 代表發(fā)送端發(fā)送的數(shù)據(jù)格式坑雅。
         * accept(MediaType.APPLICATION_JSON_UTF8) 代表客戶端希望接受的數(shù)據(jù)類型格式辈挂。
         * mockMvc.perform() 建立 Web 請(qǐng)求。
         * andExpect(...) 可以在 perform(...) 函數(shù)調(diào)用后多次調(diào)用裹粤,表示對(duì)多個(gè)條件的判斷终蒂。
         * status().isOk() 判斷請(qǐng)求狀態(tài)是否返回 200。
         * andReturn 該方法返回 MvcResult 對(duì)象遥诉,該對(duì)象可以獲取到返回的視圖名稱拇泣、返回的 Response 狀態(tài)、獲取攔截請(qǐng)求的攔截器集合等矮锈。
         */
        // map的參數(shù)
        final MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("id", "6");
        params.add("hello", "world");
        String responseString = mockMvc.perform(
                                    MockMvcRequestBuilders.get("/hello")
                                    // 設(shè)置參數(shù)
                                    .params(params)
                                    // 設(shè)置headers
                                    // 代表發(fā)送端發(fā)送的數(shù)據(jù)格式
                                    .contentType(MediaType.APPLICATION_JSON_UTF8)
                                    // 代表客戶端希望接受的數(shù)據(jù)類型格式
                                    .accept(MediaType.APPLICATION_JSON_UTF8))
                                // 把請(qǐng)求及返回內(nèi)容打印出來
                                .andDo(print())
                                // 添加表達(dá)式測(cè)試霉翔,測(cè)試狀態(tài)是否正常
                                .andExpect(status().isOk())
                                // 判斷返回文本是否包含
                                .andExpect(content().string(containsString("hello")))
                                // 判斷返回文本是否相等
                                //.andExpect(content().string(equalTo("hello")))
                                // 返回值是json時(shí)判斷的內(nèi)容
                                .andExpect(MockMvcResultMatchers.jsonPath("$.nickname").value("獨(dú)孤九劍"))
                                // 將response的content返回
                                .andReturn().getResponse().getContentAsString();



        System.out.println("result : "+responseString);

    }
}


二、service測(cè)試

測(cè)試的需要@Service注解
service1:
接口HelloService.java

package com.lonelyflow.dcoker.service;

public interface HelloService {
    public void sayHello();
}

實(shí)現(xiàn)HelloServiceImpl.java,實(shí)現(xiàn)類一定要有@Service注解

package com.lonelyflow.dcoker.service.impl;

import com.lonelyflow.dcoker.service.HelloService;
import org.springframework.stereotype.Service;

@Service
public class HelloServiceImpl implements HelloService {
    @Override
    public void sayHello() {
        System.out.println("hello service");
    }
}

service2:

import org.springframework.stereotype.Service;

@Service
public class MyService {

    public void sayHi(){
        System.out.println("安好");
    }
}

測(cè)試:service自動(dòng)注入可以使用@Resource也可以使用@Autowired

package com.lonelyflow.dcoker.Controller;

import com.lonelyflow.dcoker.service.HelloService;
import com.lonelyflow.dcoker.tool.MyService;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.rule.OutputCapture;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;

import static org.assertj.core.api.Assertions.assertThat;

@RunWith(SpringRunner.class)
@SpringBootTest
public class ServiceTests {
    /**
     * 測(cè)試自動(dòng)注入服務(wù)
     * @throws Exception
     */
    // 自動(dòng)注入
    @Resource
    private HelloService helloService;
    @Autowired
    private MyService myService;
    // 搜集控制臺(tái)打印的信息
    @Rule
    public OutputCapture outputCapture = new OutputCapture();
    @Test
    public void testService() throws  Exception{
        helloService.sayHello();
        myService.sayHi();
        assertThat(this.outputCapture.toString().contains("hello service")).isTrue();
    }
}


讀取properties
讀取properties的類

package com.lonelyflow.dcoker.tool;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Component
// 關(guān)聯(lián)的properties或yml文件路徑,不指定默認(rèn)加載@PropertySource("classpath:application.properties")
@PropertySource("classpath:other.properties")
// 指定加載的屬性文件里前綴
@ConfigurationProperties(prefix = "other")
public class HelloProperties {
    private  String title;
    private  String url;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }
}

測(cè)試的類

package com.lonelyflow.dcoker.Controller;

import com.lonelyflow.dcoker.tool.HelloProperties;
import com.lonelyflow.dcoker.tool.HelloYML;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;


@RunWith(SpringRunner.class)
/**
 * 測(cè)試類都需要添加
 */
@SpringBootTest
public class PropertiesTests {



    @Test
    public void hello() {
        System.out.println("hello world");
    }
    /**
     *  測(cè)試讀取配置屬性信息苞笨,自動(dòng)注入
     */
    // 對(duì)properties文件自動(dòng)注入
    @Value("${hello.title}")
    private String title;
    // 自動(dòng)注入properties
    @Resource
    private HelloProperties helloProperties;
    @Test
    public void testProperties() throws Exception{
        System.out.println("value hello.title:"+title);
        System.out.println("Resource-property: title:"+helloProperties.getTitle());
        System.out.println("Resource-property: url:"+helloProperties.getUrl());
    }

}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末债朵,一起剝皮案震驚了整個(gè)濱河市子眶,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌序芦,老刑警劉巖臭杰,帶你破解...
    沈念sama閱讀 218,640評(píng)論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異谚中,居然都是意外死亡渴杆,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,254評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門宪塔,熙熙樓的掌柜王于貴愁眉苦臉地迎上來磁奖,“玉大人,你說我怎么就攤上這事某筐〉懔龋” “怎么了?”我有些...
    開封第一講書人閱讀 165,011評(píng)論 0 355
  • 文/不壞的土叔 我叫張陵来吩,是天一觀的道長(zhǎng)敢辩。 經(jīng)常有香客問我,道長(zhǎng)弟疆,這世上最難降的妖魔是什么戚长? 我笑而不...
    開封第一講書人閱讀 58,755評(píng)論 1 294
  • 正文 為了忘掉前任,我火速辦了婚禮怠苔,結(jié)果婚禮上同廉,老公的妹妹穿的比我還像新娘。我一直安慰自己柑司,他們只是感情好迫肖,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,774評(píng)論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著攒驰,像睡著了一般蟆湖。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上玻粪,一...
    開封第一講書人閱讀 51,610評(píng)論 1 305
  • 那天隅津,我揣著相機(jī)與錄音,去河邊找鬼劲室。 笑死伦仍,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的很洋。 我是一名探鬼主播充蓝,決...
    沈念sama閱讀 40,352評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了谓苟?” 一聲冷哼從身側(cè)響起官脓,我...
    開封第一講書人閱讀 39,257評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎娜谊,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體斤讥,經(jīng)...
    沈念sama閱讀 45,717評(píng)論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡纱皆,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,894評(píng)論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了芭商。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片派草。...
    茶點(diǎn)故事閱讀 40,021評(píng)論 1 350
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖铛楣,靈堂內(nèi)的尸體忽然破棺而出近迁,到底是詐尸還是另有隱情,我是刑警寧澤簸州,帶...
    沈念sama閱讀 35,735評(píng)論 5 346
  • 正文 年R本政府宣布鉴竭,位于F島的核電站,受9級(jí)特大地震影響岸浑,放射性物質(zhì)發(fā)生泄漏搏存。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,354評(píng)論 3 330
  • 文/蒙蒙 一矢洲、第九天 我趴在偏房一處隱蔽的房頂上張望璧眠。 院中可真熱鬧,春花似錦读虏、人聲如沸责静。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,936評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)灾螃。三九已至,卻和暖如春揩徊,著一層夾襖步出監(jiān)牢的瞬間睦焕,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,054評(píng)論 1 270
  • 我被黑心中介騙來泰國(guó)打工靴拱, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留垃喊,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,224評(píng)論 3 371
  • 正文 我出身青樓袜炕,卻偏偏與公主長(zhǎng)得像本谜,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子偎窘,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,974評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容