springboot使用@SpringBootTest注解进行单元测试「建议收藏」

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

大家好,又见面了,我是你们的朋友全栈君。

概述

@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
2019-02-19 16:18:35.376  INFO 6676 --- [       Thread-5] com.alibaba.druid.

 

我的座右铭:不会,我可以学;落后,我可以追赶;跌倒,我可以站起来;我一定行。

springboot使用@SpringBootTest注解进行单元测试「建议收藏」

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/129597.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • Java获取二维数组行列长度「建议收藏」

    Java获取二维数组行列长度「建议收藏」二维数组intarray[][]=newint[3][3];行长度:array.length列长度:array[i].lengthclassTest{for(inti=0;i

    2022年5月12日
    49
  • 获取系统当前时间,绑定展示数据

    获取系统当前时间,绑定展示数据

    2021年9月30日
    40
  • Python获取时间戳及常用的时间格式转换[通俗易懂]

    Python获取时间戳及常用的时间格式转换[通俗易懂]常用的时间格式转换:时间戳:10位13位16位ISO格式UTC时间代码如下:#!/usr/bin/envpython#coding=utf-8″””#:author:TerryLi#:url:https://blog.csdn.net/qq_42183962#:copyright:©2020-presentTerryLi#:motto:IbelievethattheGodrewardsthediligent.”””import

    2022年10月2日
    2
  • mongodb百亿数据存储(mysql数据库并发量)

    3 过程分析与测试3.1 GridFS概述由于MongoDB中的Bson对象大小是有限制的,在1.7版本以前单个Bson对象最大容量为4M,1.7版本以后单个Bson对象最大容量为16M[5]。对于一般的文件存储,单个对象的4到16M的存储容量能够满足需求,但无法满足对于一些大文件的存储,如高清图片、设计图纸、视频等,因此在海量数据存储方面,MongoDB提供了内置的GridFS,

    2022年4月14日
    1.1K
  • 阿基里斯追乌龟的思考,空间,时间,速度非连续

    阿基里斯追乌龟的思考,空间,时间,速度非连续高中的时候才接触和了解,诺阿基里斯追乌龟的悖论,一直萦绕在自己的心头。在上大学的时候,学习了微积分,自己以为自己懂了,但是最近又思考的时候,发现大学里的那种想法还是存在着一些矛盾,自己没有意识到。再度思考,将自己的想法记录下来,如果存在问题,还请多多指教。按照积分将追逐的过程映射为无限级数的和,然后极限求解,但是极限本身就是一个无限接近但是不可到达的过程,因此在我看来…

    2022年6月18日
    31
  • idea2021通用激活码【2021.7最新】[通俗易懂]

    (idea2021通用激活码)这是一篇idea技术相关文章,由全栈君为大家提供,主要知识点是关于2021JetBrains全家桶永久激活码的内容https://javaforall.net/100143.htmlIntelliJ2021最新激活注册码,破解教程可免费永久激活,亲测有效,上面是详细链接哦~MLZPB5EL5Q-eyJsaWNlb…

    2022年3月21日
    69

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号