使用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中的逻辑代码,外部接口的调用也是相同的逻辑

 

posted @ 2019-03-20 17:43  默默行走  阅读(5819)  评论(0编辑  收藏  举报