美文网首页Spring Boot
(二)搭建测试环境

(二)搭建测试环境

作者: 傅永德 | 来源:发表于2016-10-17 14:58 被阅读0次

    Spring Boot Test 简介

    Spring Boot提供了大量的实用的注解来帮助我们测试程序。针对测试支持由两个模块提供,spring-boot-test包含核心项目,而spring-boot-test-autoconfigure支持测试的自动配置。

    大多数开发人员只使用spring-boot-starter-test即可,它会导入两个Spring Boot测试模块以及JUnit,AssertJ,Hamcrest和一些其他有用的库。

    搭建测试环境

    ​ 基于上文中的例子,我们来搭建测试环境。

    1、在pom.xml文件中,添加spring-boot-starter-test的依赖,它包含了一系列的测试库(JUnit 、Spring TestAssertJ 、HamcrestMockito 、JSONassert 、JsonPath )。

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

    2、我们简单的先针对Controller层进行单元测试。测试Spring MVC只需在对应的测试类上添加@WebMvcTest注解即可。由于是基于Spring Test环境下的单元测试,请不要忘记添加@RunWith(SpringRunner.class)注解。

    test\java\com\jason\web目录下新建IndexControllerTest.java文件。

    package com.jason.web;
    
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
    import org.springframework.http.MediaType;
    import org.springframework.test.context.junit4.SpringRunner;
    import org.springframework.test.web.servlet.MockMvc;
    
    import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
    import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
    import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
    
    @RunWith(SpringRunner.class)
    @WebMvcTest(IndexController.class)
    public class IndexControllerTest {
    
        @Autowired
        private MockMvc mvc;
    
        @Test
        public void testIndex() throws Exception {
            this.mvc.perform(get("/index").accept(MediaType.TEXT_PLAIN))
                    .andExpect(status().isOk()).andExpect(content().string("Hello, Spring Boot!"));
        }
    
    }
    

    3、运行IndexControllerTest.java中的testIndex()方法,即可看到测试结果。

    本文示例程序请点此获取。
    详细资料请参考Spring Boot官网

    相关文章

      网友评论

        本文标题:(二)搭建测试环境

        本文链接:https://www.haomeiwen.com/subject/wetzyttx.html