zoukankan      html  css  js  c++  java
  • 使用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中的逻辑代码,外部接口的调用也是相同的逻辑

  • 相关阅读:
    React中的PropTypes详解
    mobile 更改hosts
    sed用例
    Centos 7 开启端口
    node-gyp rebuild 卡住?
    录制客户端脚本
    创建删除表空间以及表空间使用情况查询
    oracle 修改字符集 修改为ZHS16GBK
    linux中压缩、解压缩命令详解
    jps、jstack、jmap、jhat、jstat、hprof使用详解
  • 原文地址:https://www.cnblogs.com/nihaofenghao/p/10566436.html
Copyright © 2011-2022 走看看