zoukankan      html  css  js  c++  java
  • springboot-32-使用mvc测试

    Spring Boot可以和大部分流行的测试框架协同工作:通过Spring JUnit创建单元测试;生成测试数据初始化数据库用于测试;Spring Boot可以跟BDD(Behavier Driven Development)工具、Cucumber和Spock协同工作,对应用程序进行测试。

    进行软件开发的时候,我们会写很多代码,不过,再过六个月(甚至一年以上)你知道自己的代码怎么运作么?通过测试(单元测试、集成测试、接口测试)可以保证系统的可维护性,当我们修改了某些代码时,通过回归测试可以检查是否引入了新的bug。总得来说,测试让系统不再是一个黑盒子,让开发人员确认系统可用。

    在web应用程序中,对Controller层的测试一般有两种方法:(1)发送http请求;(2)模拟http请求对象。第一种方法需要配置回归环境,通过修改代码统计的策略来计算覆盖率;第二种方法是比较正规的思路,但是在我目前经历过的项目中用得不多,今天总结下如何用Mock对象测试Controller层的代码。

    在之前的几篇文章中,我们都使用bookpub这个应用程序作为例子,今天也不例外,准备测试它提供的RESTful接口是否能返回正确的响应数据。这种测试不同于单元测试,需要为之初始化完整的应用程序上下文、所有的spring bean都织入以及数据库中需要有测试数据,一般来说这种测试称之为集成测试或者接口测试


    mvc测试代码: 
    package com.letv.bigdata.idfa.test.controller;
    
    import com.letv.bigdata.idfa.controller.IdfaController;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
    import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.boot.test.mock.mockito.MockBean;
    import org.springframework.test.context.junit4.SpringRunner;
    
    import org.junit.*;
    import org.junit.runner.*;
    import org.springframework.test.context.web.WebAppConfiguration;
    import org.springframework.test.web.servlet.MockMvc;
    import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
    import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
    import org.springframework.test.web.servlet.setup.MockMvcBuilders;
    import org.springframework.web.context.WebApplicationContext;
    
    @RunWith(SpringRunner.class)
    @SpringBootTest
    @AutoConfigureMockMvc
    @WebAppConfiguration
    public class IdfaControllerTest {
    
        private MockMvc mvc;
        @Autowired
        private WebApplicationContext context;
    
        @Test
        public void test() throws Exception {
            mvc.perform(MockMvcRequestBuilders.get("/query"))
                    .andExpect(MockMvcResultMatchers.status().isOk());
    //                .andExpect(MockMvcResultMatchers.content().string("abc"));
        }
    
    
        @Before
        public void setupMockMvc() throws Exception {
            mvc = MockMvcBuilders.webAppContextSetup(context).build();
        }
    
    
    }

    可以进行简单的get测试, 其他待测

     
  • 相关阅读:
    mongodb分布式查询
    MongoDB JAVA API Filters
    mongodb.conf配置文件详解
    mongodb安装配置
    Elasticsearch-2.3.x填坑之路
    C++对象模型详解
    关于虚函数的那些事儿
    关于B树的一些总结
    动态规划问题
    C中的qsort函数和C++中的sort函数的理解与使用
  • 原文地址:https://www.cnblogs.com/wenbronk/p/9023475.html
Copyright © 2011-2022 走看看