zoukankan      html  css  js  c++  java
  • Spring Boot 编写Mock测试

    引入Maven依赖:

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

    测试Controller的代码

    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class TestControllerTest {
    
        @Autowired
        private WebApplicationContext webApplicationContext;
    
        private MockMvc mockMvc;
    
        @Before
        public void setupMockMvc(){
            mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
        }
    
         @Test
        public void testTes() throws Exception{
            mockMvc.perform(MockMvcRequestBuilders.get("/api/test") // 发出请求
                    .contentType(MediaType.APPLICATION_JSON_UTF8) //期望的内容类型
                    .accept(MediaType.APPLICATION_JSON_UTF8)) //期望接收的内容类型
                    .andExpect(MockMvcResultMatchers.status().isOk()) //期望结果是200
                    .andDo(MockMvcResultHandlers.print()); // 期望把结果打印出来
         }
    }

    Mock测试打印输出的日志:

    MockHttpServletRequest:
          HTTP Method = GET
          Request URI = /api/test
           Parameters = {}
              Headers = [Content-Type:"application/json;charset=UTF-8", Accept:"application/json;charset=UTF-8"]
                 Body = null
        Session Attrs = {}
    
    Handler:
                 Type = com.fubin.controller.TestController
               Method = public java.lang.Object com.fubin.controller.TestController.test()
    
    Async:
        Async started = false
         Async result = null
    
    Resolved Exception:
                 Type = null
    
    ModelAndView:
            View name = null
                 View = null
                Model = null
    
    FlashMap:
           Attributes = null
    
    MockHttpServletResponse:
               Status = 200
        Error message = null
              Headers = [Content-Type:"application/json;charset=UTF-8"]
         Content type = application/json;charset=UTF-8
                 Body = {"id":2,"name":"fubin","age":28,"url":"https://fubin.org.cn"}
        Forwarded URL = null
       Redirected URL = null
              Cookies = []
  • 相关阅读:
    c#冒泡排序算法和快速排序算法
    sqlserver 索引
    varchar和Nvarchar区别
    trigger
    sql语句
    超实用压力测试工具-ab工具
    js 页面离开前触发事件
    C# websocket与html js实现文件发送与接收处理
    C# socket编程 使用fleck轻松实现对话 https://github.com/statianzo/Fleck
    C# socket编程 使用udp实现单对单的连接对话
  • 原文地址:https://www.cnblogs.com/fubinhnust/p/12013999.html
Copyright © 2011-2022 走看看