使用junit和Mock做接口测试

时间:2022-12-10 05:07:52

一般创建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);
    }