日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

spring boot单元测试

發布時間:2024/10/5 编程问答 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 spring boot单元测试 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

做一個穩健的開發,寫一首漂亮的單元測試是少不了的

首先要分清幾個概念:測試方法、測試類、測試集、測試運行器。

  • 測試方法就是用 @Test 注解的一些函數。
  • 測試類是包含一個或多個測試方法的一個 XxTest.java 文件
  • 測試集是一個suite, 可能包含多個測試類。
  • 測試運行器則決定了用什么方式偏好去運行這些測試集/類/方法。

Spring Boot 模塊獨立測試

Spring Boot 支持各模塊單獨隔離測試,例如web, db。單獨測試各模塊時不需要啟動整個spring上下文,通過禁用一些spring boot自動配置來實現。

Spring Boot Test Slices Overview and Usage
https://rieckpil.de/spring-boot-test-slices-overview-and-usage/

@WebMvcTest 測試web層

@WebMvcTest?測試web層,controller層,不包括service層。

@WebMvcTest 注解主要用于controller層測試,只覆蓋應用程序的controller層,HTTP請求和響應是Mock出來的,因此不會創建真正的連接。因此需要創建 MockMvc bean進行模擬接口調用。
如果Controller層對Service層中的其他bean有依賴關系,那么需要使用Mock提供所需的依賴項。
WebMvcTest要快得多,因為我們只加載了應用程序的一小部分。
?

@DataJpaTest 測試jpa

@DataJpaTest?測試jpa @Repository EntityManager TestEntityManager DataSource

@DataJpaTest?注解會禁用 spring boot 的其他自動配置,只保留 jpa 測試相關的。

默認情況下?@DataJpaTest?注解的測試類都是事務型的,測試方法結束后會回滾操作。
默認情況下?@DataJpaTest?會啟動一個內存數據庫,例如 H2 或 Derby,來代替其他數據庫。配合使用?@AutoConfigureTestDatabase?注解來自動配置一個測試庫。
如果想加載全部spring上下文,同時使用內存數據庫,應該使用?@SpringBootTest?搭配?@AutoConfigureTestDatabase?注解來實現。

@DataJpaTest?注解的測試類中可以直接注入?TestEntityManager?來作為?EntityManager?使用。
如果想在?@DataJpaTest?外使用 TestEntityManager, 需要添加 @AutoConfigureTestEntityManager 注解

TestEntityManager NullPointerException

一開始注入的 TestEntityManager 一直是 null,后來加上 @RunWith(SpringRunner.class) 就好了

有?@DataJpaTest?而不啟動 Spring 上下文時,可以直接注入 TestEntityManager 使用
如果不使用?@DataJpaTest?而是啟動Spring上下文的話,就沒有 TestEntityManager 實例可注入了,需要改為注入 EntityManager

Test Your Spring Boot JPA Persistence Layer With @DataJpaTest
https://rieckpil.de/test-your-spring-boot-jpa-persistence-layer-with-datajpatest/


@JdbcTest 測試jdbc

@JdbcTest?測試jdbc


@DataMongoTest 測試mongo

@DataMongoTest?測試mongo

@DataMongoTest?注解會禁用 spring boot 的其他自動配置,只保留 mongo 測試相關的。


@JsonTest 測試json

@JsonTest?測試json序列化、反序列化


@RestClientTest 測試http客戶端

@RestClientTest?測試http客戶端


@SpringBootTest 測試springboot應用

@SpringBootTest?測試spring boot應用,各種service層。


@Transactional 測試數據自動回滾

可以實現再springboot中使用junit編寫單元測試,并且測試結果不影響數據庫。

@Transactional 表示該方法整體為一個事務,可以用在測試類上表示所有測試方法都回滾,或具體的 @Test 方法上。
@Rollback 表示事務執行完回滾,支持傳入一個參數value,默認true即回滾,false不回滾。

springboot中junit回滾
https://www.jianshu.com/p/d9d0abf317c0


使用MockMvc測試Spring MVC Controller

用到的注解:
@RunWith(SpringJUnit4ClassRunner.class): 表示使用Spring Test組件進行單元測試;
@WebAppConfiguration: 使用這個Annotate會在跑單元測試的時候真實的啟動一個web服務,然后開始調用Controller的Rest API,待單元測試跑完之后再將web服務停掉;
@ContextConfiguration: 指定Bean的配置文件信息,可以有多種方式,這個例子使用的是文件路徑形式,如果有多個配置文件,可以將括號中的信息配置為一個字符串數組來表示;controller,component等都是使用注解,需要注解指定spring的配置文件,掃描相應的配置,將類初始化等。
@TransactionConfiguration(transactionManager=”transactionManager”,defaultRollback=true)配置事務的回滾,對數據庫的增刪改都會回滾,便于測試用例的循環利用

為什么要進行事務回滾:
1、測試過程對數據庫的操作,會產生臟數據,影響我們數據的正確性
2、不方便循環測試,即假如這次我們將一個記錄刪除了,下次就無法再進行這個Junit測試了,因為該記錄已經刪除,將會報錯。
3、如果不使用事務回滾,我們需要在代碼中顯式的對我們的增刪改數據庫操作進行恢復,將多很多和測試無關的代碼

測試類基類

import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.transaction.TransactionConfiguration; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.context.WebApplicationContext;//這個必須使用junit4.9以上才有 @RunWith(SpringJUnit4ClassRunner.class) //單元測試的時候真實的開啟一個web服務 @WebAppConfiguration //配置事務的回滾,對數據庫的增刪改都會回滾,便于測試用例的循環利用 @TransactionConfiguration(transactionManager="transactionManager",defaultRollback=true) @Transactional @ContextConfiguration(locations = {"classpath:spring.xml","classpath:spring-hibernate.xml"}) public class AbstractContextControllerTests {@Autowired protected WebApplicationContext wac; } 具體測試類package com.pengtu.gsj;import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;import org.hibernate.SessionFactory; import org.junit.Before; import org.junit.Test; import org.owasp.esapi.ESAPI; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders;import com.pengtu.gsj.controller.BannerController; import com.pengtu.gsj.dao.UserDao; import com.pengtu.gsj.entity.app.User; import com.pengtu.gsj.service.UserService;public class EsapiTest extends AbstractContextControllerTests{private MockMvc mockMvc; //該方法在每個方法執行之前都會執行一遍 @Before public void setUp() throws Exception { mockMvc = MockMvcBuilders.standaloneSetup(new BannerController()).build(); }/** * perform:執行一個RequestBuilder請求,會自動執行SpringMVC的流程并映射到相應的控制器執行處理; * get:聲明發送一個get請求的方法。MockHttpServletRequestBuilder get(String urlTemplate, Object... urlVariables):根據uri模板 和uri變量值得到一個GET請求方式的。另外提供了其他的請求的方法,如:post、put、delete等。 * param:添加request的參數,如上面發送請求的時候帶上了了pcode = root的參數。假如使用需要發送json數據格式的時將不能使用這種 方式,可見后面被@ResponseBody注解參數的解決方法 * andExpect:添加ResultMatcher驗證規則,驗證控制器執行完成后結果是否正確(對返回的數據進行的判斷); * andDo:添加ResultHandler結果處理器,比如調試時打印結果到控制臺(對返回的數據進行的判斷); * andReturn:最后返回相應的MvcResult;然后進行自定義驗證/進行下一步的異步處理(對返回的數據進行的判斷) * @throws Exception */ @Test public void getAllBanners() throws Exception{ String responseString = mockMvc.perform(get("/banner/hello") //請求的url,請求的方法是get .contentType(MediaType.APPLICATION_JSON) //數據的格式 .param("id","123456789") //添加參數 ).andExpect(status().isOk()) //返回的狀態是200 .andDo(print()) //打印出請求和相應的內容 .andReturn().getResponse().getContentAsString(); //將相應的數據轉換為字符串 System.out.println("--------返回的json = " + responseString); } }

perform:執行一個RequestBuilder請求,會自動執行SpringMVC的流程并映射到相應的控制器執行處理;
get:聲明發送一個get請求的方法。MockHttpServletRequestBuilder get(String urlTemplate, Object… urlVariables):根據uri模板和uri變量值得到一個GET請求方式的。另外提供了其他的請求的方法,如:post、put、delete等。
param:添加request的參數,如上面發送請求的時候帶上了了pcode = root的參數。假如使用需要發送json數據格式的時將不能使用這種方式。
andExpect:添加ResultMatcher驗證規則,驗證控制器執行完成后結果是否正確(對返回的數據進行的判斷);
andDo:添加ResultHandler結果處理器,比如調試時打印結果到控制臺(對返回的數據進行的判斷);
andReturn:最后返回相應的MvcResult;然后進行自定義驗證/進行下一步的異步處理(對返回的數據進行的判斷)

使用MockMvc測試Spring mvc Controller
https://blog.csdn.net/zhang289202241/article/details/62042842


SpringRunner和SpringJUnit4ClassRunner

SpringRunner 是 SpringJUnit4ClassRunner 的別名,兩者沒有任何區別

What is the difference between SpringJUnit4ClassRunner and SpringRunner
https://stackoverflow.com/questions/47446529/what-is-the-difference-between-springjunit4classrunner-and-springrunner

Class SpringRunner
https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/test/context/junit4/SpringRunner.html


spring boot單元測試

1、要讓一個普通類變成一個單元測試類只需要在類名上加入?@SpringBootTest?和?@RunWith(SpringRunner.class)?兩個注釋即可。
2、在測試方法上加上?@Test?注釋。

Spring Boot 單元測試詳解+實戰教程
https://www.cnblogs.com/javastack/p/9150408.html


@SpringBootTest

@SpringBootTest?為 springApplication 創建上下文并支持 SpringBoot 特性

@SpringBootTest?注解告訴 SpringBoot 去尋找一個主配置類(例如帶有?@SpringBootApplication?的配置類),并使用它來啟動 Spring 應用程序上下文。SpringBootTest 加載完整的應用程序并注入所有可能的bean,因此速度會很慢。
在這種情況下,不需要創建 MockMvc bean,可以直接通過 RestTemplate 進行請求測試(或者使用 TestRestTemplate )。

使用 @SpringBootTest 的 webEnvironment 屬性定義運行環境:
Mock(默認): 加載 WebApplicationContext 并提供模擬的 web 環境 Servlet環境,使用此批注時,不會啟動嵌入式服務器
RANDOM_PORT: 加載 WebServerApplicationContext 并提供真實的 web 環境,嵌入式服務器,監聽端口是隨機的
DEFINED_PORT: 加載 WebServerApplicationContext 并提供真實的 Web 環境,嵌入式服務器啟動并監聽定義的端口(來自 application.properties 或默認端口 8080)
NONE: 使用 SpringApplication 加載 ApplicationContext 但不提供任何Web環境

Spring Test單元測試
http://jianwl.com/2016/08/07/Spring-Test%E5%8D%95%E5%85%83%E6%B5%8B%E8%AF%95/

Annotation Type SpringBootTest
https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/test/context/SpringBootTest.html


@TestPropertySource 設置System Property

@TestPropertySource 可以用來覆蓋掉來自于系統環境變量、Java系統屬性、@PropertySource的屬性。

同時@TestPropertySource(properties=…)優先級高于@TestPropertySource(locations=…)。

利用它我們可以很方便的在測試代碼里微調、模擬配置(比如修改操作系統目錄分隔符、數據源等)。

Spring、Spring Boot和TestNG測試指南 - @TestPropertySource
https://segmentfault.com/a/1190000010854607

@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath:whereever/context.xml") @TestPropertySource(properties = {"myproperty = foo"}) public class TestWarSpringContext { ... }

How to set environment variable or system property in spring tests?
https://stackoverflow.com/questions/11306951/how-to-set-environment-variable-or-system-property-in-spring-tests


@ClassRule 和 @Rule

junit中的 @ClassRule,可以在所有類方法開始前進行一些初始化調用,比如創建臨時文件,

package com.jdriven;import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder;import java.io.File; import java.io.IOException;public class JUnitClassRuleTest {@ClassRule public static TemporaryFolder temporaryFolder = new TemporaryFolder();public static File tempFile;@BeforeClass public static void createTempFile() throws IOException { tempFile = temporaryFolder.newFile("tempFile.txt"); }@Test public void testJUnitClassRule_One() { //Your test should go here, which uses tempFile }@Test public void testJUnitClassRule_Two() { //Your test should go here and uses the same tempFile } }

其中,@ClassRule中指定創建臨時文件夾,這是在所有的測試方法前會創建文件夾,并且會在所有測試完成后,遞歸刪除其下的子目錄和子文件夾。

@Rule 是方法級別的,每個測試方法執行時都會調用被注解的Rule,而@ClassRule是類級別的,在執行一個測試類的時候只會調用一次被注解的Rule

junit中的@classrule,@rule
http://jackyrong.iteye.com/blog/2193451


@RunWith

@RunWith指定JUnit使用的單元測試執行類,使用@RunWith注解可以改變JUnit的默認執行類
@Runwith放在測試類名之前,用來確定這個類怎么運行的。也可以不標注,會使用默認運行器。

常見的運行器有:

  • 參數化運行器
    @RunWith(Parameterized.class) 參數化運行器,配合@Parameters使用junit的參數化功能

  • 測試集運行器
    @RunWith(Suite.class)
    @SuiteClasses({ATest.class,BTest.class,CTest.class})
    測試集運行器配合使用測試集功能

  • junit4的默認運行器
    @RunWith(JUnit4.class)
    junit4的默認運行器

  • 兼容junit3.8的運行器
    @RunWith(JUnit38ClassRunner.class)
    用于兼容junit3.8的運行器

  • SpringJUnit4ClassRunner
    @RunWith(SpringJUnit4ClassRunner.class)集成了spring的一些功能

junit常用注解詳細說明
http://www.cnblogs.com/tobey/p/4837495.html

使用RunWith注解改變JUnit的默認執行類,并實現自已的Listener
http://blog.csdn.net/fenglibing/article/details/8584602


@Test

在junit3中,是通過對測試類和測試方法的命名來確定是否是測試,且所有的測試類必須繼承junit的測試基類。在junit4中,定義一個 測試方法變得簡單很多,只需要在方法前加上@Test就行了。

注意:測試方法必須是public void,即公共、無返回數據。可以拋出異常。

junit常用注解詳細說明
http://www.cnblogs.com/tobey/p/4837495.html


@ContextConfiguration

@ContextConfiguration?注解用于指定 spring 配置文件所在的路徑,有以下幾個常用的屬性:

locations 配置文件路徑

locations?可以通過該屬性手工指定 Spring 配置文件所在的位置,可以指定一個或多個 Spring 配置文件。如下所示:

@ContextConfiguration(locations = {"xx/yy/beans1.xml","xx/yy/beans2.xml"}) @ContextConfiguration(locations = "classpath*:spring-ctx-*.xml")

inheritLocations 是否繼承父類配置

inheritLocations:是否要繼承父測試用例類中的 Spring 配置文件,默認為 true。如下面的例子:

@ContextConfiguration(locations={"base-context.xml"}) public class BaseTest { // ... } @ContextConfiguration(locations={"extended-context.xml"}) public class ExtendedTest extends BaseTest { // ... }

如果 inheritLocations 設置為 false,則 ExtendedTest 僅會使用 extended-context.xml 配置文件,否則將使用 base-context.xml 和 extended-context.xml 這兩個配置文件。

classes 指定配置類

classes 屬性可指定一些 Configuration 配置類,例如:

@SpringBootTest @ContextConfiguration(classes = MyConfiguration.class) public class ConsulLockTest { }


Spring基于注解TestContext 測試框架使用詳解
http://blog.csdn.net/yaerfeng/article/details/25368447

Spring 注解學習手札(六) 測試
http://snowolf.iteye.com/blog/588351

總結

以上是生活随笔為你收集整理的spring boot单元测试的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。