首先maven要引入spring-boot-starter-test这个包。

先看一段代码

@RunWith(SpringRunner.class)

@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)

public class MyTest {

        @Autowired

    private TestRestTemplate restTemplate;

    @Test 

  public void test() {

        this.restTemplate.getForEntity( 

           "/{username}/vehicle", String.class, "Phil");

    }

}

1、@RunWith(SpringRunner.class) 告诉JUnit运行使用Spring的测试支持。SpringRunner是SpringJUnit4ClassRunner的新名字,这个名字只是让名字看起来简单些。

2、@SpringBootTest的意思是“带有Spring Boot支持的引导程序”(例如,加载应用程序、属性,为我们提供Spring Boot的所有精华部分)。

3、webEnvironment属性允许为测试配置特定的“网络环境”。你可以利用一个MOCK小服务程序环境开始你的测试,或者使用一个运行在RANDOM_PORT 或者 DEFINED_PORT上的真正的HTTP服务器。

4、如果我们想要加载一个特定的配置,我们可以用@SpringBootTest class属性。在这个实例中,我们省略classes就意味着测试要首次尝试从任意一个inner-classes中加载@ configuration,如果这个尝试失败了,它会在你主要的@SpringBootApplicationclass中进行搜索。

------------------------------------------------------------------------------------------------------------------------------

其中IndexController是你写的controller

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class IndexTest { private MockMvc mvc; @Autowired
private IndexController indexController; @Before
public void setup() {
this.mvc = MockMvcBuilders.standaloneSetup(indexController).build();
} @Test
public void t() throws Exception {
assertNotNull(mvc); mvc.perform(MockMvcRequestBuilders.get("/h").
accept(MediaType.parseMediaType("application/json;charset=UTF-8")))
.andExpect(MockMvcResultMatchers.status().isOk()); }
}

这个是第二种测试方法:

package com.hexun.bdc.auth.controller;

import com.hexun.bdc.auth.client.Application;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.embedded.LocalServerPort;
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.web.client.TestRestTemplate;
import org.springframework.test.context.junit4.SpringRunner;
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 static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertNotNull; /**
* Created by iceblue on 2017/3/26.
webEnvironment=RANDOM_PORT表示启动服务时端口随机(避免端口冲突)
*/ @RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = Application.class)
@AutoConfigureMockMvc
public class IndexControllerTest { @Autowired
protected MockMvc mvc; @LocalServerPort // 注入端口
private Integer port; @Autowired
private TestRestTemplate restTemplate; private static final Logger logger = LoggerFactory.getLogger(IndexControllerTest.class); @Test
public void t() throws Exception {
assertNotNull(mvc); logger.info("# port:" + port.toString()); assertThat(this.restTemplate.getForObject("http://localhost:" + port + "/h",
String.class)).contains("hello");
// mvc.perform(MockMvcRequestBuilders.get("/h"))
// .andExpect(MockMvcResultMatchers.status().isOk());
} }

是第三种测试方法,直接利用TestRestTemplate类

package com.hexun.bdc.auth.controller;

import com.hexun.bdc.auth.client.Application;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.test.context.junit4.SpringRunner; import static org.junit.Assert.assertNotNull; @RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,classes = Application.class)
public class IndexTest2 { @Autowired
private TestRestTemplate restTemplate;
private static final Logger logger = LoggerFactory.getLogger(IndexTest2.class); @Test
public void t() throws Exception {
assertNotNull(restTemplate);
String body = this.restTemplate.getForObject("/h", String.class);
System.out.println("body = " + body);
logger.info("body = " + body); } }

Spring Boot(七):spring boot测试介绍的更多相关文章

  1. Spring系列(七) Spring MVC 异常处理

    Servlet传统异常处理 Servlet规范规定了当web应用发生异常时必须能够指明, 并确定了该如何处理, 规定了错误信息应该包含的内容和展示页面的方式.(详细可以参考servlet规范文档) 处 ...

  2. 从零开始学spring cloud(七) -------- Spring Cloud OpenFegin

    一.OpenFegin 介绍 Feign是一个声明性的Web服务客户端. 它使编写Web服务客户端变得更容易. 要使用Feign,请创建一个界面并对其进行注释. 它具有可插入的注释支持,包括Feign ...

  3. spring学习七 spring和dynamic project进行整合

    spring和web项目进行整合,其实就是在项目启动时,就创建spring容器,然后在servlet中使用spring容器进行开. 注意:为了页面可以访问到servlet,因此servlet必须放进t ...

  4. Spring学习(七)-----Spring Bean的5种作用域

    在Spring中,bean作用域用于确定哪种类型的 bean 实例应该从Spring容器中返回给调用者.bean支持的5种范围域: 单例(singleton) - 每个Spring IoC 容器返回一 ...

  5. Spring学习(七)--Spring MVC的高级技术

    一.Spring MVC配置的替代方案 我们已经了解如何通过AbstractAnnotationConfigDispatcherServlet- Initializer快速搭建了Spring MVC环 ...

  6. spring入门(七) spring mvc+mybatis+generator

    1.Mybatis-Generator下载 地址:https://github.com/mybatis/generator/releases 我使用的是 mybatis-generator-core- ...

  7. spring boot(五)Spring data jpa介绍

    在上篇文章springboot(二):web综合开发中简单介绍了一下spring data jpa的基础性使用,这篇文章将更加全面的介绍spring data jpa 常见用法以及注意事项 使用spr ...

  8. Redis篇之操作、lettuce客户端、Spring集成以及Spring Boot配置

    Redis篇之操作.lettuce客户端.Spring集成以及Spring Boot配置 目录 一.Redis简介 1.1 数据结构的操作 1.2 重要概念分析 二.Redis客户端 2.1 简介 2 ...

  9. 一键式Spring集成工具 Spring Boot

    最近公司使用Spring boot进行开发,稍微了解一下,不过自我感觉把集中式配置applicate.properties搞明白,注解用过Spring MVC的boot绝对没问题的 比如拦截器:@As ...

  10. Spring Kafka和Spring Boot整合实现消息发送与消费简单案例

    本文主要分享下Spring Boot和Spring Kafka如何配置整合,实现发送和接收来自Spring Kafka的消息. 先前我已经分享了Kafka的基本介绍与集群环境搭建方法.关于Kafka的 ...

随机推荐

  1. Linq 时间参数的一个坑

    背景:查询某个字段大于系统时间的数据 两种写法: 1.DataTime now=DateTime.Now; var result=dbContext.Table1.Created>now 2.  ...

  2. JCA 了解

    JCA (J2EE 连接器架构,Java Connector Architecture)是对 J2EE标准集的重要补充.因为它注重的是将 Java程序连接到非Java程序和软件包中间件的开发.连接器特 ...

  3. JQUERY中的事件处理:RETURN FALSE、阻止默认行为、阻止冒泡以及兼容性问题

    return false 在jQuery中,我们常用return false来阻止浏览器的默认行为,那"return false"到底做了什么? 当你每次调用"retur ...

  4. Jquery事件冒泡

    事件冒泡 什么是事件冒泡 在一个对象上触发某类事件(比如单击onclick事件),如果此对象定义了此事件的处理程序,那么此事件就会调用这个处理程序,如果没有定义此事件处理程序或者事件返回true,那么 ...

  5. in_array() 和array_search的区别

    在判断字符串是否在某个数组里面的时候,我们会经常用到in_array()和array_search这两个函数. 他们的用法都是在数组中搜索给定的值,但是不同的是, in_array()给定的值 val ...

  6. [Functional Programming ADT] Debug a Functional JavaScript composeK Flow

    When using ADTs in our code base, it can be difficult to use common debugging tools like watches and ...

  7. 怎样用Jenkins触发还有一个Jenkins---Global build solution

    由于上次发的帖子太受欢迎,导致有非常多人问也有很多其它的人想知道.2个不同地域位置的Jenkins怎样自己主动触发相互的Job.当今非常多公司做的产品仅仅是全球化工作的一部分.须要这部分做好以后去做另 ...

  8. js中字符串转换为数字

    js 字符串转化成数字的三种方法主要有 转换函数.强制类型转换.利用js变量弱类型转换. 1. 转换函数: js提供了parseInt()和parseFloat()两个转换函数.前者把值转换成整数,后 ...

  9. 【转】Spring的中IoC及AOP

    1. Spring介绍 Spring是轻量级的J2EE应用程序框架.Spring的核心是个轻量级容器(container),实现了IoC(Inversion of Control)模式的容器,Spri ...

  10. taro 创建 Tabbar

    1.代码 src/app.js import '@tarojs/async-await' import Taro, { Component } from '@tarojs/taro' import H ...