Spring Boot 單元測試

學習完整課程請移步 互聯網 Java 全棧工程師

本節視頻

概述

主要是通過 @RunWith@SpringBootTest 注解來開啟單元測試功能

package com.funtl.hello.spring.boot;

import org.junit.Before;
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.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;

import java.net.URL;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = HelloSpringBootApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class HelloSpringBootApplicationTests {

    @LocalServerPort
    private int port;

    private URL base;

    @Autowired
    private TestRestTemplate template;

    @Before
    public void setUp() throws Exception {
        this.base = new URL("http://localhost:" + port + "/");
    }

    @Test
    public void contextLoads() {
        ResponseEntity<String> response = template.getForEntity(base.toString(), String.class);
        assertThat(response.getBody(), equalTo("Hello Spring Boot"));
    }

}

運行它會先啟動 Spring Boot 工程,再啟動單元測試

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 單元測試對于開發人員來說是非常熟悉的,我們每天的工作也都是圍繞著開發與測試進行的,在最早的時候測試都是采用工具De...
    OzanShareing閱讀 4,786評論 0 1
  • 單元測試 單元測試注意事項 測試方法必須用@Test修飾 測試方法必須使用public void修飾,不能帶參數 ...
    聰明的奇瑞閱讀 1,415評論 0 2
  • 測試是保證程序健壯的手段之一,也是非常重要的。今天我們來簡單的聊聊Spring boot 如何進行測試。 引入測試...
    Mason啊閱讀 4,101評論 2 1
  • Spring Boot 提供了一些實用程序和注解,用來幫我們測試應用程序。測試由兩個模塊支持——spring-bo...
    wesker8080閱讀 697評論 0 5
  • 前天夢到自己做家排,被選為代表,愛的代表。醒來后感覺自己充滿了愛的能量。金科老師解讀說:“夢的智慧老人通過做家排代...
    初夏的曦閱讀 220評論 0 0