国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

SpringBoot單元測試--Mockito+Junit5框架使用

這篇具有很好參考價值的文章主要介紹了SpringBoot單元測試--Mockito+Junit5框架使用。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點(diǎn)擊"舉報違法"按鈕提交疑問。

前言

作為程序員為了提前發(fā)現(xiàn)代碼bug,優(yōu)化代碼; 通常我們寫完某個功能模塊代碼后都需要寫單元測試對代碼塊進(jìn)行測試(特別是敏捷開發(fā)中);Java項(xiàng)目最常用的單元測試框架即為Junit(目前最新版本為Junit5),SpringBoot本身也整合了該框架。在寫單元測試時代碼塊中的調(diào)到第三方接口方法或涉及數(shù)據(jù)庫操作的接口方法一般都需要mock掉(測試中叫打測試樁)。目前在 Java 中主流的 Mock 測試框架有 Mockito、JMock、EasyMock,Mockito 框架是SpringBoot 目前內(nèi)建的 框架。本文主要介紹Junit5+Mockito在SpringBoot項(xiàng)目寫單元測試的使用。

maven依賴

Mockito,Junit在SpringBoot 內(nèi)部已依賴只需引入spring-boot-starter-test即可。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
    <exclusions>
      <exclusion>
        <groupId>org.junit.vintage</groupId>
        <artifactId>junit-vintage-engine</artifactId>
        </exclusion>
      </exclusions>
</dependency>
<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-api</artifactId>
    <scope>test</scope>
</dependency>

Junit5基本使用

基本注解:

類注解:

@TestInstance(Lifecycle.PER_CLASS)注解

如果您希望JUnit Jupiter在同一個測試實(shí)例上執(zhí)行所有測試方法,只需使用@TestInstance(Lifecycle.PER_CLASS)注釋您的測試類。使用此模式時,每個測試類將創(chuàng)建一個新的測試實(shí)例。如果沒使用@TestInstance(Lifecycle.PER_CLASS)注解,使用@BeforeAll和@AfterAll注解必須在static靜態(tài)方法上使用。

  • TestInstance.Lifecycle.PER_CLASS:每個測試類將創(chuàng)建一個新的測試實(shí)例。
  • TestInstance.Lifecycle.PER_METHOD:將為每種測試方法,測試工廠方法或測試模板方法創(chuàng)建一個新的測試實(shí)例。此模式類似于JUnit版本1至4中的行為。
@ExtendWith(MockitoExtension.class)注解

用在springboot項(xiàng)目中,涉及spring的單元測試需要使用@ExtendWith(SpringExtension.class)注解,可以mock spring bean。不涉及spring時使用@ExtendWith(MockitoExtension.class)。

@ExtendWith(SpringExtension.class)注解在Spring boot?2.1.x需要配合@SpringBootTest 使用,Spring boot?2.1.x之后可以不使用@ExtendWith(SpringExtension.class)注解

參考文檔:Java – 理解 @ExtendWith(SpringExtension.class) 和 @ExtendWith(MockitoExtension.class)之間的差別

@SpringBootTest(classes = Application.class)注解

classes = ApplicationStarter.class指向SpringBoot啟動類,啟動spring容器。

在不同的Spring Boot版本中@ExtendWith的使用:

其中在Spring boot?2.1.x之前:?

@SpringBootTest?需要配合@ExtendWith(SpringExtension.class)才能正常工作的。

而在Spring boot?2.1.x之后:?

@SpringBootTest 已經(jīng)組合了@ExtendWith(SpringExtension.class),因此,無需在進(jìn)行該注解的使用了,進(jìn)一步簡化。如下圖@SpringBootTest注解中已包含@ExtendWith(SpringExtension.class):

?

@extendwith(mockitoextension.class),測試開發(fā),軟件開發(fā),單元測試,spring boot,junit,spring,java

方法注解:

基本的注解都是方法上的注解,意思就是只在測試方法上進(jìn)行添加,對應(yīng)注解有以下幾種:

注解 說明
@Test 測試方法的入口;可單獨(dú)運(yùn)行
@BeforeEach 每個測試方法前運(yùn)行;不可以單獨(dú)運(yùn)行該方法
@AfterEach 每個測試方法后運(yùn)行;不可以單獨(dú)運(yùn)行該方法
@BeforeAll? 在類中所有方法前運(yùn)行;static修飾;不可單獨(dú)運(yùn)行該方法
@AfterAll 在類中所有方法后運(yùn)行;static修飾;不可單獨(dú)運(yùn)行該方法

代碼示例:

import org.mockito.InjectMocks;

@TestInstance(Lifecycle.PER_CLASS)
@SpringBootTest(classes = ApplicationStarter.class)
public class DemoServiceImplTest {

    @InjectMocks
    private DemoService demoService =new DemoServiceImpl();

    @BeforeAll
    void beforeAllInit() {
        System.out.println("running before all");
    }

    @AfterAll
    void afterAllCleanUp() {
        System.out.println("running after all");
    }

    @BeforeEach
    void init() {
        System.out.println("running before each...");
    }

    @AfterEach
    void cleanUp() {
        System.out.println("running after each...");
    }

    @Test
    void testSum() {
        assertEquals(2, demoService.addtwoNumbers(1, 1));
    }

}

斷言校驗(yàn):

Assertions.assertEquals()值比較校驗(yàn):

assertEquals(expected, actual,message)里面最少是2個參數(shù),一個自己的期望值「expected」,一個程序的實(shí)際值「?actual」。如果想要斷言失敗的情況下顯示自定義的說明,則加上第3個參數(shù),即斷言失敗說明「message」。

Assertions.assertThrows()異常捕獲校驗(yàn):

assertThrows(Class<T> expectedType, Executable executable, String message)

去判斷代碼拋出的異常是業(yè)務(wù)代碼自定義的異常不,對應(yīng)的期望值變成了異常類型「Class<T>」的期望值,實(shí)際的值也是拋出異常的實(shí)際值「Executable」,同樣如果想要斷言失敗的情況下顯示自定義的說明,則加上第3個參數(shù),即斷言失敗說明「message」。

代碼示例:

import org.mockito.InjectMocks;

@TestInstance(Lifecycle.PER_CLASS)
@SpringBootTest(classes = ApplicationStarter.class)
public class DemoServiceImplTest {

    @InjectMocks
    private DemoService demoService =new DemoServiceImpl();

    
    @Test
    public void testSum() {
        //Assertions.assertThrows()
        Exception ex = Assertions.assertThrows(Exception.class, () ->demoService.addtwoNumbers(1, 1))
        //Assertions.assertEquals()
        Assertions.assertEquals(ex.getMessage(),"test");
    }

}

更多詳細(xì)信息參考文檔:test-instance-lifecycle

Mockito使用

在測試代碼塊中經(jīng)常會調(diào)到第三方接口方法(比如第三方SDK接口方法或遠(yuǎn)程RPC接口),涉及數(shù)據(jù)庫操作的接口方法(數(shù)據(jù)庫增刪改查接口)。這些方法需要其他環(huán)境服務(wù)支持,鏈接遠(yuǎn)程數(shù)據(jù)庫,我們只需測試自己編寫的單元代碼塊是否有問題,不想真實(shí)調(diào)用這些方法。要解決這個問題,可以把這些方法都mock(模擬)掉。Mockito框架提供很好的支持。

常用注解

  • @Mock:創(chuàng)建一個Mock,用于替換被測試類中的引用的bean或第三方類。
  • @InjectMocks:用于創(chuàng)建一個被測試類的實(shí)例,其余用@Mock(或@Spy)注解創(chuàng)建的mock將被注入到用該實(shí)例中。用于被測試類(如service層的ServiceImpl)
  • @Mockbean:將Mock對象添加到Spring上下文中。Mock將替換Spring上下文中任何相同類型的現(xiàn)有bean,如果沒有定義相同類型的bean,將添加一個新的bean。如果需要使用Mockbean注解,需要使用SpringRunner(Junit5 中是@ExtendWith(SpringExtension.class)
    )

@Autowird 等方式完成自動注入。在單元測試中,沒有啟動 spring 框架,此時就需要通過 @ InjectMocks完成依賴注入。@InjectMocks會將帶有@Spy 和@Mock 注解的對象嘗試注入到被 測試的目標(biāo)類中。如下代碼示例:

代碼示例:



@Component("mock")
public class MockRepository {


    public MockData mock(String userName) {
        return new MockData(userName);
        
    }

}
import org.mockito.InjectMocks;

@Service
public class DemoServiceImpl {


    @Autowired
    private UserRepository userRepository;


    @Autowired
    private ApplicationContext applicationContext;
    

    @Override
    public Result getUserInfo(String id) {
        User user=userRepository.findUserById(id);
        MockRepository mockRepository=applicationContext.getBean("mock");
        MockData data=mockRepository.mock(user.getUserName());
        return new Result("1000","success",data);
        
    }

}
import org.mockito.InjectMocks;

@TestInstance(Lifecycle.PER_CLASS)
@SpringBootTest(classes = ApplicationStarter.class)
public class DemoServiceImplTest {

    @InjectMocks
    private DemoService demoService =new DemoServiceImpl();

    @Mock
    private UserRepository userRepository;

    @MockBean
    private MockRepository mockRepository;

    @Autowired
    private ApplicationContext applicationContext;
    
    @Test
    public void testSum() {
        //Assertions.assertThrows()
        Result res =demoService.getUserInfo("test");
        //Assertions.assertEquals()
        Assertions.assertEquals(res.getCode(),"1000");
    }

}

Mock方法:

1.when(...) thenReturn(...)會調(diào)用真實(shí)的方法,如果你不想調(diào)用真實(shí)的方法而是想要mock的話,就不要使用這個方法。


import org.mockito.InjectMocks;

@TestInstance(Lifecycle.PER_CLASS)
@SpringBootTest(classes = ApplicationStarter.class)
public class DemoServiceImplTest {

    @InjectMocks
    private DemoService demoService =new DemoServiceImpl();

    @Mock
    private UserRepository userRepository;

    @MockBean
    private MockRepository mockRepository;

    @Autowired
    private ApplicationContext applicationContext;
    
    @Test
    public void testSum() {
        // when(..).thenReturn(..)
        Mockito.when(userRepository.findUserById(Mockito.anyString())).thenReturn(new User());    
        Result res =demoService.getUserInfo("test");
        //Assertions.assertEquals()
        Assertions.assertEquals(res.getCode(),"1000");
    }

}


2.doReturn(...) when(...) 跟when(...) thenReturn(...)一樣都是mock方法,但不會調(diào)用真實(shí)方法。

import org.mockito.InjectMocks;

@TestInstance(Lifecycle.PER_CLASS)
@SpringBootTest(classes = ApplicationStarter.class)
public class DemoServiceImplTest {

    @InjectMocks
    private DemoService demoService =new DemoServiceImpl();

    @Mock
    private UserRepository userRepository;

    @MockBean
    private MockRepository mockRepository;

    @Autowired
    private ApplicationContext applicationContext;
    
    @Test
    public void testSum() {
        // doReturn(new User()).when(userRepository)    
        Mockito.doReturn(new User()).when(userRepository).findUserById(Mockito.anyString()))
        Result res =demoService.getUserInfo("test");
        //Assertions.assertEquals()
        Assertions.assertEquals(res.getCode(),"1000");
    }

}

3.doAnswer…when?當(dāng)模擬對象調(diào)用它的方法,需要執(zhí)行一些操作(其實(shí)就是需要執(zhí)行一個代碼塊)才能得到返回值時,則需要使用doAnswer來構(gòu)造產(chǎn)生這個模擬的返回值。例如:當(dāng)模擬對象調(diào)用某個方法的返回值是個復(fù)合值(bean)時,就需要用doAnswer來構(gòu)造該返回值。文章來源地址http://www.zghlxwxcb.cn/news/detail-781927.html

@InjectMocks
private DemoService demoService =new DemoServiceImpl();

@Mock
private StockDao stockDao;
...

@Test
public void stockTest() {
    
        doAnswer(new Answer<StockModel>) {
            @Override
            public StockModel answer(InvocationOnMock invocation) throws Throwable {
                StockModel  stock = new StockModel ();
                stock.setFundFamilyName("fundFamily01");
                return stock;
            }
        }).when(stockDao).lookup("testStock");
        Result res=demoService.stock("testStock");
        Assertions.assertEquals(res.getStock(),"test");
    
}

到了這里,關(guān)于SpringBoot單元測試--Mockito+Junit5框架使用的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請點(diǎn)擊違法舉報進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

  • 深度揭秘JUnit5與Mockito的單元測試神秘面紗

    深度揭秘JUnit5與Mockito的單元測試神秘面紗

    在今天的學(xué)習(xí)中,我們將深入研究 JUnit 和Mockito,這是 Java 開發(fā)中最強(qiáng)大的 單元測試 工具之一。通過學(xué)習(xí)如何編寫清晰、高效的單元測試,我們將揭開單元測試的神秘面紗,助力你在項(xiàng)目中寫出更健壯的代碼。 提示: 今天的代碼是在第九天代碼的基礎(chǔ)上進(jìn)行開發(fā),我們將為

    2024年02月02日
    瀏覽(33)
  • 【單元測試】如何使用 JUnit5 框架?

    【單元測試】如何使用 JUnit5 框架?

    ??Junit5是一個用于在Java平臺上進(jìn)行單元測試的框架。JUnit 5 框架主要由三部分組成:JUnit Platform、JUnit Jupiter 和 JUnit Vintage。 JUnit Platform:定義了測試引擎的 API,是 JVM 上用于啟動測試框架的基礎(chǔ)服務(wù),支持通過 IDE、構(gòu)建工具、命令行等方式運(yùn)行單元測試。 JUnit Jupiter:包含

    2024年04月10日
    瀏覽(27)
  • 單元測試框架——Junit5

    單元測試框架——Junit5

    Junit是一個開源的用于Java語言的單元測試框架,也是Java方向使用最廣泛的單元測試框架。 在pom.xml中引入Junit5相關(guān)依賴 @Test :表示一個方法/用例 BeforeEach :表示被注解的方法在其它所有方法執(zhí)行前都要執(zhí)行一遍,也就是說其它方法有3個它就要執(zhí)行3遍 @BeforeAll :表示被注解的

    2024年02月11日
    瀏覽(25)
  • Junit5單元測試框架詳解

    Junit5單元測試框架詳解

    前面我們學(xué)習(xí)了Selenium自動化測試框架,但是有的時候測試用例會很多,我們需要一個工具來管理這些測試用例,而Junit就是一個很好的管理工具,簡單點(diǎn)來說,Junit就是一個針對Java的單元測試框架; 目錄 一.?關(guān)于Junit5 二. Junit使用 2.1 添加Maven依賴 2.2 注解 2.3 斷言 2.4 套件

    2024年02月06日
    瀏覽(27)
  • SpringBoot2---單元測試(Junit5)(1)

    SpringBoot2---單元測試(Junit5)(1)

    org.junit.vintage junit-vintage-engine test org.hamcrest hamcrest-core org.springframework.boot spring-boot-starter-test test 現(xiàn)在版本: @SpringBootTest class Boot05WebAdminApplicationTests { @Test void contextLoads() { } } 以前: @SpringBootTest + @RunWith(SpringRunner.class) SpringBoot整合Junit以后。 編寫測試方法:@Test標(biāo)注(注意需要

    2024年04月29日
    瀏覽(17)
  • 13.Springboot整合junit5單元測試與生成單元測試覆蓋率

    13.Springboot整合junit5單元測試與生成單元測試覆蓋率

    現(xiàn)在基本大公司都要求單元測試了,保證我們代碼得質(zhì)量,而我司更是要求覆蓋率要達(dá)到60%以上,所以搞一下。 這里有兩個方法: 1.使用maven自帶得test,idea右側(cè)maven模塊執(zhí)行項(xiàng)目下得test 2.使用cmd命令,在你的項(xiàng)目pom文件所在目錄 ,打開cmd,執(zhí)行如下: 結(jié)果如下:打開site文

    2024年02月16日
    瀏覽(23)
  • 【SpringBoot】mockito+junit 單元測試

    【SpringBoot】mockito+junit 單元測試

    CommonServiceImpl 在方法 getSourceCodeMap() 調(diào)用了 ServiceA 的方法 list(QueryBO queryBo) 。 org.mockito.exceptions.base.MockitoException: No tests found in ClientSyncServiceImplTest Is the method annotated with @Test? Is the method public? 解決方案: Test引入 org.junit.Test 不要引入 org.junit.jupiter.api.Test 例如獲取當(dāng)前用戶 moc

    2024年02月09日
    瀏覽(30)
  • 靜態(tài)方法 單元測試 springboot+mokito+junit5

    CodecUtils的方法是靜態(tài)類,使用@InjectMocks不能有用,因?yàn)檫@個注解只能用于非靜態(tài)的對象。 想要為靜態(tài)方法寫單元測試,可以使用Mockito.mockStatic(Class classToMock)方法,它可以返回一個MockedStatic對象,用于模擬靜態(tài)方法的調(diào)用。 1.導(dǎo)入依賴 2.單元測試 可以參考如下地址,了解如何

    2024年04月25日
    瀏覽(21)
  • 單元測試junit(原始版本、Spring Boot各版本、junit5)使用介紹

    單元測試junit(原始版本、Spring Boot各版本、junit5)使用介紹

    ?? 簡介:java系列技術(shù)分享(??持續(xù)更新中…??) ?? 初衷:一起學(xué)習(xí)、一起進(jìn)步、堅(jiān)持不懈 ?? 如果文章內(nèi)容有誤與您的想法不一致,歡迎大家在評論區(qū)指正?? ?? 希望這篇文章對你有所幫助,歡迎點(diǎn)贊 ?? 收藏 ?留言 ?? ?? 更多文章請點(diǎn)擊 單元測試 junit各版本 使用介紹 官

    2023年04月16日
    瀏覽(32)
  • 在 Java 中使用JUnit5進(jìn)行單元測試和自動化測試

    單元測試和自動化測試是現(xiàn)代軟件開發(fā)過程中必不可少的環(huán)節(jié),可以提高代碼質(zhì)量和開發(fā)效率。JUnit5是Java中流行的單元測試框架,本文將介紹如何在Java中使用JUnit5進(jìn)行單元測試和自動化測試。 2.1 單元測試的基本概念和原理 單元測試是一種測試方法,用于對軟件系統(tǒng)中的最

    2024年02月03日
    瀏覽(23)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包