SpringBoot 單元測試

2022-09-17 19:27:14 字數 1598 閱讀 7311

1.新增測試依賴

<

dependency

>

<

groupid

>org.springframework.boot

groupid

>

<

artifactid

>spring-boot-starter-test

artifactid

>

<

scope

>test

scope

>

dependency

>

2.新增啟動類和測試類

//等於下面3個

//@springbootconfiguration

//@enableautoconfiguration

//@componentscan

public

class

public

static

void

main(string args)

}

package

top.ytheng.demo;

import

org.junit.after;

import

org.junit.before;

import

org.junit.test;

import

org.junit.runner.runwith;

import

org.springframework.boot.test.context.springboottest;

import

org.springframework.test.context.junit4.springrunner;

import

junit.framework.testcase;

//底層用junit springjunit4classrunner

@runwith(springrunner.class)//

啟動整個springboot工程

})//

滑鼠選中springboottestdemo後執行run as -> junit test可以同時執行多個測試

public

class

springboottestdemo

@test

public

void

testtwo()

@before

public

void

testbefore()

//@test之後呼叫

//一般進行資源的**利用

@after

public

void

testafter()

}

3.選中需要測試的方法,右鍵->run as->junit test即可

Spring Boot 單元測試

由於spring boot在啟動時通常會先行啟動一些內建的元件,比如tomcat。因此,spring boot的測試類一般需要加一些簡單的註解。org.springframework.boot spring boot starter test test runwith標記乙個執行期springrun...

springboot單元測試

springboot對單元測試的支援十分完善,需要引入的jar包 org.springframework.boot spring boot starter test test 使用方式 在測試類的類頭部需要新增 runwith springrunner.class 和 springboottest註...

Spring Boot 單元測試

在所有測試方法前執行一次,一般在其中寫上整體初始化的 beforeclass 在所有測試方法後執行一次,一般在其中寫上銷毀和釋放資源的 afterclass 在每個測試方法前執行,一般用來初始化方法 比如我們在測試別的方法時,類中與其他測試方法共享的值已經被改變,為了保證測試結果的有效性,我們會在 ...