(二)搭建测试环境

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官网

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,256评论 19 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,999评论 6 342
  • 此篇翻译的是Spring Boot官方指南 Part III. 使用 Spring Boot (Using Spr...
    K天道酬勤阅读 6,869评论 0 21
  • Spring 技术笔记Day 1 预热知识一、 基本术语Blob类型,二进制对象Object Graph:对象图...
    OchardBird阅读 1,021评论 0 2
  • 最近,总觉得自己阅读能力在逐渐丧失,算是件可怕的事情,目前一起看的两本书是《不安之书》和《亲爱的生活》。 先说说前...
    大葱拌咖啡阅读 445评论 0 0