Spring Boot 1.4 单元测试

时间:2022-09-08 12:25:05

在1.3中单元测试这样子的类似代码:

// SpringJUnit支持,由此引入Spring-Test框架支持!
@RunWith(SpringJUnit4ClassRunner.class)
// 指定我们SpringBoot工程的Application启动类
@SpringApplicationConfiguration(classes = App.class)
//由于是Web项目,Junit需要模拟ServletContext,因此我们需要给我们的测试类加上@WebAppConfiguration。
@WebAppConfiguration
public class HelloServiceTest {
}

在1.4中SpringApplicationConfiguration标记为过时了,所以官方就不建议这么使用了,那么在1.4中单元测试怎么使用呢?类似代码如下:

一、建立一个整合了mybatis的工程

详见:http://www.cnblogs.com/lspz/p/6723603.html

二、编写测试类

测试类的文件结构,保持src/test/Java和src/main/java结构一直,即:包+文件夹。

如:com.example包service中类的测试,那么在src/test/java也是建立com.example包,再在包下建立文件夹service.

1、服务类的

package com.example.mapper;

import com.example.dto.User;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class)
@SpringBootTest
public class TestUserMapper {
@Autowired
private UserMapper userMapper; @Test
public void testGetById() {
User user = userMapper.getById(1L);
Assert.assertTrue("数据集不对", user.getAge() == 18);
Assert.assertTrue("数据一致", user.getName().equals("张三"));
}
}

2.controller类的

package com.example.web;

import com.example.dto.User;
import com.example.mapper.UserMapper;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; @RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
public class TestExample { @Autowired
private MockMvc mvc; @Autowired
private UserMapper userMapper; @Test
public void testGetById() throws Exception {
User user = userMapper.getById(1L);
String uri = "/getUser/1";
MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.get(uri).accept(MediaType.APPLICATION_JSON))
.andReturn();
int status = mvcResult.getResponse().getStatus();
String content = mvcResult.getResponse().getContentAsString();
Assert.assertTrue("错误,正确的返回值为200", status == 200);
Assert.assertFalse("数据不一致", !user.toString().equals(content));
}
}

controller类的第二种写法

package com.example.web;

import java.net.URL;

import com.example.dto.User;
import com.example.mapper.UserMapper;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.embedded.LocalServerPort;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner; import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat; @RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class TestExample2 {
@LocalServerPort
private int port; private URL base; @Autowired
private TestRestTemplate template; @Autowired
private UserMapper userMapper; @Before
public void setUp() throws Exception {
this.base = new URL("http://localhost:" + port + "/getUser/1");
} @Test
public void getHello() throws Exception {
User user = userMapper.getById(1L);
ResponseEntity<String> response = template.getForEntity(base.toString(),
String.class);
int status = response.getStatusCodeValue();
String content = response.getBody();
assertEquals("错误,正确的返回值为200", status, 200);
assertThat(content, equalTo(user.toString()));
}
}

三、总结

(1)依赖包的引入:pom.xml中仅依赖spring-boot-starter-test,它把相关的依赖全部引入。

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

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

(4)通过webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT我们可以让内置的服务器在随机端口启动。

(5)@LocalServerPort注释注入实际的端口

(6)如果你需要测试JSON 序列化是否如预期般运营,你可以使用 @JsonTest

  • 自动配置Jackson和/或Gson。
  • 添加你可以定义的任一模块或者 @JsonComonent beans。
  • 触发任何JacksonTester或GsonTester字段的初始化。

(7)测试您应用程序的JPA插件(Hibernate +Spring数据)可以使用@DataJpaTest注释。@DataJpaTest将会这样:

  • 配置一个内存数据库。
  • 自动配置Hibernate,Spring数据和数据源。
  • 执行@EntityScan。
  • 打开SQL日志记录。

部分内容参考自:http://www.jointforce.com/jfperiodical/article/1455

Spring Boot 1.4 单元测试的更多相关文章

  1. 【spring boot】10&period;spring boot下的单元测试

    spring boot下的单元测试,思前想后还是需要单独用一章篇幅来看看. 然后在看了介绍和使用时候,我感觉并不想多去看了. 但是还是给后来人留下参考的路径: 官网说明:https://spring. ...

  2. Spring Boot实战之单元测试

    Spring Boot实战之单元测试 本文介绍使用Spring测试框架提供的MockMvc对象,对Restful API进行单元测试 Spring测试框架提供MockMvc对象,可以在不需要客户端-服 ...

  3. Spring boot Junit Test单元测试

    Spring boot 1.40 JUnit 4 需要依赖包 spring-boot-starter-test.spring-test 建立class,加上如下注解,即可进行单元测试,别的帖子里说要加 ...

  4. 83&period; Spring Boot 1&period;4单元测试【从零开始学Spring Boot】

    在[27. Spring Boot Junit单元测试]中讲过1.3版本的单元测试方式,这里说说1.4和1.3有什么区别之处? 在1.3中单元测试这样子的类似代码: //// SpringJUnit支 ...

  5. Spring Boot 入门之单元测试篇(五)

    博客地址:http://www.moonxy.com 一.前言 JUnit 是一个由 Java 语言编写的开源的回归测试(回归测试是指重复以前全部或部分的相同测试)框架,由Erich Gamma 和 ...

  6. spring boot 集成 mybatis 单元测试Dao层 控制台报错:org&period;apache&period;ibatis&period;binding&period;BindingException&colon; Invalid bound statement &lpar;not found&rpar;&colon;

    最近帮同学做毕业程序,采用后端spring boot + mybatis + H2,将框架搭好进行各层的单元测试时,在dao层就出现了错,如图 于是在网上找各种资料,有的说是xml文件和接口没有一一对 ...

  7. 【maven】【spring boot】【单元测试】 使用controller 执行单元测试类

    存在这样一个场景: 当项目启动时间过长,又没办法缩短的时候,写单元测试就是一个十分耗时的工作, 这工作不在于使用编写代码,而在于每次run junit test 都需要完整启动一次项目,白白浪费宝贵的 ...

  8. spring boot 单元测试,如何使用profile

    一.问题概述 spring boot项目.单元测试的时候,我发现,总是会使用application.properties的内容,而该文件里,一般是我的开发时候的配置. 比如上图中,dev是开发配置,p ...

  9. Spring Boot 的单元测试和集成测试

    学习如何使用本教程中提供的工具,并在 Spring Boot 环境中编写单元测试和集成测试. 1. 概览 本文中,我们将了解如何编写单元测试并将其集成在 Spring Boot 环境中.你可在网上找到 ...

随机推荐

  1. GIT常用命令笔记

    最近在做了一个自己的项目.两个人合作的,所以需要用到版本管理工具.本来打算学一下自己搭建svn的,后来朋友推荐我用git,免费,流行,好用,逼格.所以就学习了一下.发现这个git与已经使用惯了的svn ...

  2. TCP状态变迁流程

    主动建立TCP链接情况: 被动建立TCP链接情况 主动断开链接的情况 被动断开连接的情况 在TIME_WAIT阶段需要停留2倍的MSL,MSL即Maximum Segment Lifetime,表示任 ...

  3. LINQ to Entities 不识别方法的解决方案

    //这样不行 var   BrushProducTimeout = aliexpressEntities.CP_BrushProduc.Where(p => p.isActive == true ...

  4. 超轻量级Json框架SmartObject

    最近我在codeplex上发了一个项目SmartObject(基于framework4.5,目前是1.0版本).用法如下: // HowToUse using Spider.Data; //json ...

  5. 树莓派中编译OpenCV3&period;4&period;1和OpenCvSharp

    一.简介 本文重点描述在树莓派中编译OpenCV3.4.1和OpenCvSharp,大家都知道OpenCVSharp是使用C#调用OpenCV最简洁的一个库.但是在Linux上或者树莓派上运行时,需要 ...

  6. Gym &period;102021 &period;German Collegiate Programming Contest &lpar;GCPC 18&rpar; (寒假gym自训第三场)

    B .Battle Royale 题意:给你两个点A,B,以及一个圆S,保证两个点在圆外,且其连线与圆相交,求两点间最短距离. 思路:显然是要分别与圆相切,然后在圆弧想走,直到相交. 那么ans=与圆 ...

  7. 禁止ajax访问shiro管理的登录页面

    在使用shiro的时候,对于用户权限的管理,相信很多人都已经很熟悉了.今天,我这里简单的记录一下我自己调试过程中遇到的问题.主要是登录的操作,禁止通过ajax的方式进行访问. shiro中,登录过程拒 ...

  8. 阿里云的云虚拟主机安装dede提示数据库连接失败的解决办法

    问题描述 阿里云的云虚拟主机安装dede提示数据库连接失败 问题分析 连接数据库失败,可能数据库密码不对或数据库服务器出错! 解决方案 1.通过ftp软件查看htdocs/data/common.in ...

  9. Gradle 庖丁解牛(构建生命周期核心托付对象创建源代码浅析)

    [工匠若水 http://blog.csdn.net/yanbober 未经同意严禁转载,请尊重作者劳动成果.私信联系我] 1 背景 上一篇<Gradle 庖丁解牛(构建源头源代码浅析)> ...

  10. 关于cg语言中求法向量 N&equals;mul&lpar;worldMatrix&lowbar;IT&comma;normal&rpar;&semi; 的随笔

    解释一下标题,N是变换到世界坐标后的法向量,worldMatrix_IT是变换矩阵worldMatrix的逆的转置矩阵,normal就是模型坐标的法向量. 对于点p,我们根据变换矩阵M(即worldM ...