首先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. C# 高德地图调用帮助类 GaodeHelper

    /// <summary> /// 高德地图调用帮助类 /// 更多详情请参考 高德api /// </summary> public class GaodeHelper { ...

  2. HDU 4658 Integer Partition (2013多校6 1004题)

    Integer Partition Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others ...

  3. HDU 3473 Minimum Sum(划分树)

    Minimum Sum Time Limit: 16000/8000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Tota ...

  4. json字符串生成C#实体类的工具

    转载:http://www.cnblogs.com/finesite/archive/2011/07/31/2122984.html json作为互联网上轻量便捷的数据传输格式,越来越受到重视.但在服 ...

  5. 基于tiny4412的Linux内核移植(支持device tree)(三)

    作者信息 作者: 彭东林 邮箱:pengdonglin137@163.com QQ:405728433 平台简介 开发板:tiny4412ADK + S700 + 4GB Flash 要移植的内核版本 ...

  6. TSynAuthentication SESSION验证

    TSynAuthentication SESSION验证 服务端维护的SESSIONS,实质上是一个array of integer,保存的是客户端的SESSIONID. SESSIONID可以由客户 ...

  7. 【mysql】mysql增加version字段实现乐观锁,实现高并发下的订单库存的并发控制,通过开启多线程同时处理模拟多个请求同时到达的情况 + 同一事务中使用多个乐观锁的情况处理

    mysql增加version字段实现乐观锁,实现高并发下的订单库存的并发控制,通过开启多线程同时处理模拟多个请求同时到达的情况 ==================================== ...

  8. [ Android Memory] MAT查看图片资源

    参考: http://stackoverflow.com/questions/12709603/mat-eclipse-memory-analyzer-how-to-view-bitmaps-from ...

  9. Openshift部署Zookeeper和Kafka

    部署Zookeeper github网址 https://github.com/ericnie2015/zookeeper-k8s-openshift 1.在openshift目录中,首先构建imag ...

  10. 万里长征第二步——django个人博客(第三步 —— 设置一些全局变量)

    可以将一些全局变量设置在settingg.py里 #网站的基本信息配置 SITE_NAME = 'John的个人博客' SITE_DESC = '专注学习Python开发,欢迎和大家交流' WEIBO ...