SpringBoot使用@SpringBootTest注解开发单元测试教程

概述

@SpringBootTest注解是SpringBoot自1.4.0版本开始引入的一个用于测试的注解。基本用法如下:

1.添加依赖:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.cxh.test</groupId>
  <artifactId>generator</artifactId>
  <version>0.0.1-SNAPSHOT</version>

 <parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.1.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>

  <dependencies>

		 <!-- spring boot web 依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
        <!-- 修改后立即生效,热部署 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>springloaded</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>
        <!-- 视图 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

         <!-- mybatis 依赖 -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
        	<version>1.3.0</version>
        </dependency>
        <!-- mysql 依赖 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        	<version>5.0.4</version>
        </dependency>
        <!-- alibaba的druid数据库连接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.9</version>
        </dependency>

	</dependencies>
  <dependencyManagement>
		<dependencies>
			<dependency>
				<groupId>org.springframework.cloud</groupId>
				<artifactId>spring-cloud-dependencies</artifactId>
				<version>Camden.SR6</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
		</dependencies>
	</dependencyManagement>
  <build/>
</project>

2. 编写启动入口类

package com.cxh.study.platform;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 *
 * @desciption
 * @author ChenXiHua
 *
 */
@SpringBootApplication
public class GeneratorApp {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		SpringApplication.run(GeneratorApp.class, args);
	}

}

3. 编写Controller类

package com.cxh.study.platform;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 *
 * @desciption
 * @author ChenXiHua
 *
 */
@SpringBootApplication
public class GeneratorApp {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		SpringApplication.run(GeneratorApp.class, args);
	}

}

4. 编写service类

package com.cxh.study.platform.service;

import java.util.List;

import com.cxh.study.platform.entity.User;

public interface IUserService {

	// 获取所有用户
	List<User> getAll();

	// 根据id获取用户
	User getUserById(Integer id);
}
package com.cxh.study.platform.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cxh.study.platform.entity.User;
import com.cxh.study.platform.mapper.IUserMapper;
import com.cxh.study.platform.service.IUserService;

@Service("userServiceImpl")
public class UserServiceImpl implements IUserService {

	@Autowired
	private IUserMapper userMapper;

	@Override
	public List<User> getAll() {
		return userMapper.getAll();
	}

	@Override
	public User getUserById(Integer id) {
		return userMapper.getUserById(id);
	}

}

5. 编写mapper类

package com.cxh.study.platform.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Mapper;

import com.cxh.study.platform.entity.User;

@Mapper
public interface IUserMapper {
	//获取所有用户
	List<User>getAll();
	//根据id获取用户
	User getUserById(Integer id);
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.cxh.study.platform.mapper.IUserMapper" >
	<!--获取所有用户  -->
	<select id="getAll" resultType="com.cxh.study.platform.entity.User">
		SELECT * FROM s_user
	</select>
	<!-- 根据id获取单个用户 -->
	<select id="getUserById" parameterType="java.lang.Integer" resultType="com.cxh.study.platform.entity.User">
		SELECT * FROM s_user
		where id=#{id}
	</select>
</mapper>

6. 编写测试类

package com.cxh.test;

import java.net.URL;
import java.util.List;

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 com.cxh.study.platform.GeneratorApp;
import com.cxh.study.platform.entity.User;

/**
 *
 * @desciption 用户管理测试类
 * @author ChenXiHua
 * @date 2019年2月19日
 *
 */
@RunWith(SpringRunner.class)
@SpringBootTest(classes = GeneratorApp.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class UserTest {

	 /**
     * @LocalServerPort 提供了 @Value("${local.server.port}") 的代替
     */
    @LocalServerPort
    private int port;

    private URL base;

    @Autowired
    private TestRestTemplate restTemplate;

    @Before
    public void setUp() throws Exception {
        String url = String.format("http://localhost:%d/", port);
        System.out.println(String.format("port is : [%d]", port));
        this.base = new URL(url);
    }

    /**
     * 向"/test"地址发送请求,并打印返回结果
     * @throws Exception
     */
    //@Test
    public void test1() throws Exception {

        ResponseEntity<String> response = this.restTemplate.getForEntity(
                this.base.toString() + "/test", String.class, "");
        System.out.println(String.format("测试结果为:%s", response.getBody()));
    }

    //@Test
    public void getAllTest() throws Exception {

        ResponseEntity<List> response = this.restTemplate.getForEntity(
                this.base.toString() + "/getAll", List.class, "");
        System.out.println(String.format("测试结果为:%s", response.getBody()));
    }

    @Test
    public void getUserByIdTest() throws Exception {

        ResponseEntity<User> response = this.restTemplate.getForEntity(
                this.base.toString() + "/getUserById?id=1", User.class, "");
        System.out.println(String.format("测试结果为:%s", response.getBody().toString()));
    }

}

其中,classes属性指定启动类,SpringBootTest.WebEnvironment.RANDOM_PORT经常和测试类中@LocalServerPort一起在注入属性时使用。会随机生成一个端口号。

7.测试结果:

2019-02-19 16:18:27.933  INFO 6676 --- [           main] com.cxh.test.UserTest                    : Started UserTest in 25.637 seconds (JVM running for 27.647)

port is : [14067]

2019-02-19 16:18:31.366  INFO 6676 --- [o-auto-1-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring FrameworkServlet 'dispatcherServlet'

2019-02-19 16:18:31.367  INFO 6676 --- [o-auto-1-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization started

2019-02-19 16:18:31.462  INFO 6676 --- [o-auto-1-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization completed in 95 ms

测试结果为:User [id=1, account=cxh, password=123, type=1, status=1]

2019-02-19 16:18:35.326  INFO 6676 --- [       Thread-5] ationConfigEmbeddedWebApplicationContext : Closing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@191004a: startup date [Tue Feb 19 16:18:05 CST 2019]; root of context hierarchy

到此这篇关于SpringBoot使用@SpringBootTest注解开发单元测试教程的文章就介绍到这了,更多相关SpringBoot使用@SpringBootTest开发单元测试内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • 解决没有@RunWith 和 @SpringBootTest注解或失效问题

    导入别人的项目 或者 自己想创建一个测试类 经常会遇见了这个问题没有@RunWith 和 @SpringBootTest注解或失效 网上搜了搜 全是我下面的第一个解决方案 第二个才是重点 解决方案 1 添加依赖 如果 你是springboot项目 pom文件中添加 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</

  • 使用@SpringBootTest注解进行单元测试

    概述 @SpringBootTest注解是SpringBoot自1.4.0版本开始引入的一个用于测试的注解.基本用法如下: 1. 添加Maven依赖 <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <parent> <groupId>org.springframework.boot</gro

  • SpringBoot如何使用RequestBodyAdvice进行统一参数处理

    SpringBoot RequestBodyAdvice参数处理 在实际项目中 , 往往需要对请求参数做一些统一的操作 , 例如参数的过滤 , 字符的编码 , 第三方的解密等等 , Spring提供了RequestBodyAdvice一个全局的解决方案 , 免去了我们在Controller处理的繁琐 . RequestBodyAdvice仅对使用了@RqestBody注解的生效 , 因为它原理上还是AOP , 所以GET方法是不会操作的. package com.xbz.common.web;

  • springboot接口如何多次获取request中的body内容

    1. 概述 在使用springboot开发接口时,会将参数转化为Bean,用来进行参数的自动校验.同时也想获取request中原始body报文进行验签(防止报文传输过程中被篡改). 因为通过将bean再转化为字符串后,body里面的报文格式.字段顺序会发生改变,就会导致验签失败.因此只能通过request来获取body里面的内容. 既想接口自动实现参数校验,同时又想获取request中的原始报文,因此我们可以通过在controller中的restful方法中,写入两个参数,获取多次request

  • SpringBoot2.x 集成腾讯云短信的详细流程

    一.腾讯云短信简介 腾讯云短信(Short Message Service,SMS)沉淀腾讯十多年短信服务技术和经验,为QQ.微信等亿级平台和10万+客户提供快速灵活接入的高质量的国内短信与国际/港澳台短信服务. 国内短信验证秒级触达,99%到达率. 国际/港澳台短信覆盖全球200+国家/地区,稳定可靠. 单次短信的业务请求流程如下所示: 短信由签名和正文内容组成,发送短信前需要申请短信签名和正文内容模板.短信签名是位于短信正文前[]中的署名,用于标识公司或业务.短信签名需要审核通过后才可使用.

  • SpringBoot使用@SpringBootTest注解开发单元测试教程

    概述 @SpringBootTest注解是SpringBoot自1.4.0版本开始引入的一个用于测试的注解.基本用法如下: 1.添加依赖: <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.

  • SpringBoot整合Mybatis注解开发的实现代码

    官方文档: https://mybatis.org/mybatis-3/zh/getting-started.html SpringBoot整合Mybatis 引入maven依赖 (IDEA建项目的时候直接选就可以了) <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <ve

  • SpringBoot使用Mybatis注解实现分页动态sql开发教程

    目录 一.环境配置 二.Mybatis注解 三.方法参数读取 1.普通参数读取 2.对象参数读取 四.分页插件的使用 五.动态标签 六.完整示例 一.环境配置 1.引入mybatis依赖 compile( //SpringMVC 'org.springframework.boot:spring-boot-starter-web', "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.9.3", //Mybatis依赖及分页

  • 使用注解开发SpringMVC详细配置教程

    1.使用注解开发SpringMVC 1.新建一个普通的maven项目,添加web支持 2.在pom.xml中导入相关依赖 SpringMVC相关 <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.2.8.RELEASE</version> </dependency&

  • SpringBoot自定义注解开发指南

    目录 一.Java注解(Annotation) 1.JDK基本注解 2.JDK元注解 二.自定义注解开发 1.含义 2.演示 三.完成切面日志操作 四.完成前端响应反应 总结 一.Java注解(Annotation) 含义:Java注解是附加在代码中的一些元信息,用于一些工具在编译. 运行时进行解析和使用,起到说明.配置的功能. 1.JDK基本注解 @Override ——>重写 @Deprecated ——>已过时 @SuppressWarnings(value = "unchec

  • Springboot集成JUnit5优雅进行单元测试的示例

    为什么使用JUnit5 JUnit4被广泛使用,但是许多场景下使用起来语法较为繁琐,JUnit5中支持lambda表达式,语法简单且代码不冗余. JUnit5易扩展,包容性强,可以接入其他的测试引擎. 功能更强大提供了新的断言机制.参数化测试.重复性测试等新功能. ps:开发人员为什么还要测试,单测写这么规范有必要吗?其实单测是开发人员必备技能,只不过很多开发人员开发任务太重导致调试完就不管了,没有系统化得单元测试,单元测试在系统重构时能发挥巨大的作用,可以在重构后快速测试新的接口是否与重构前有

  • 详解SpringBoot项目的创建与单元测试

    前言   Spring Boot 设计之初就是为了用最少的配置,以最快的速度来启动和运行 Spring 项目.Spring Boot使用特定的配置来构建生产就绪型的项目. Hello World 1.可以在 Spring Initializr上面添加,也可以手动在 pom.xml中添加如下代码∶ <dependency> <groupId>org.springframework.boot</groupId> <artifactId>Spring-boot-s

  • Springboot启动扩展点超详细教程小结

    1.背景 Spring的核心思想就是容器,当容器refresh的时候,外部看上去风平浪静,其实内部则是一片惊涛骇浪,汪洋一片.Springboot更是封装了Spring,遵循约定大于配置,加上自动装配的机制.很多时候我们只要引用了一个依赖,几乎是零配置就能完成一个功能的装配. 我非常喜欢这种自动装配的机制,所以在自己开发中间件和公共依赖工具的时候也会用到这个特性.让使用者以最小的代价接入.想要把自动装配玩的转,就必须要了解spring对于bean的构造生命周期以及各个扩展接口.当然了解了bean

  • 解决@springboottest注解无法加载src/main/resources目录下文件

    目录 结论 环境及问题描述 问题分析 1.首先com.xx.xxx.service.SsoService该类存在 2.再看下pom文件的配置 3.这个类是在src/main/resources目录下的资源文件里配置 Springboot微服务框架是目前越来越流行的框架,省去了很多繁琐的xml配置.最近新启了个项目,采用SpringBoot框架从头搭建,中间也遇到过各种坑,现在先描述一下 Junit4单元测试之坑吧. 结论 @SpringBootTest注解,只会加载test路径下的资源文件(即x

随机推荐