使用junit和Mock做接口測試


一般創建SpringBoot項目的時候,一般都會有test包的依賴,該依賴包依賴了junit,mockito的依賴

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
</dependency>

編寫一個總的父類

package com.voole;

import org.junit.Before;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

@RunWith(SpringRunner.class)
@SpringBootTest(classes=AuthserviceConsumerApplication.class)
public class AuthserviceConsumerApplicationTests {

    @Autowired
    private WebApplicationContext wac;
    
    
    private MockMvc mockMvc;
    
    @Before
    public void setup() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
    }
    
    public MockMvc getMvc() {
        return mockMvc;
    }
    
    
    

}

之后的其他的類繼承父類后,直接編寫相關的junit測試即可

@Test
    public void testCancelOrder() throws Exception {
        MockHttpServletRequestBuilder request = MockMvcRequestBuilders.put("/1.0/ordercanal/181551852853360")
        MvcResult andReturn = this.getMvc().perform(request).andExpect(status().isOk()).andReturn();
        this.printResponse(andReturn);
    }

 

 

補充:針對於微服務中,在具體的業務處理過程中會調用外部接口的問題--提供了mockito框架

           或者只是測試單個類的業務邏輯,不調用其他的類,也可以這樣

1、業務類

 

 

 

 2、測試類

 對demoService接口的調用做了一個結果的預設,相當於只測試類demoController中的邏輯代碼,外部接口的調用也是相同的邏輯

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM