广告
返回顶部
首页 > 资讯 > 后端开发 > Python >SpringBoot使用@SpringBootTest注解开发单元测试教程
  • 155
分享到

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

2024-04-02 19:04:59 155人浏览 安东尼

Python 官方文档:入门教程 => 点击学习

摘要

目录概述1.添加依赖:2. 编写启动入口类3. 编写Controller类4. 编写service类5. 编写mapper类6. 编写测试类7.测试结果:概述 @SpringBoot

概述

@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;
 

@SpringBootApplication
public class GeneratorApp {
 
	
	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;
 

@SpringBootApplication
public class GeneratorApp {
 
	
	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;
 
 

@RunWith(SpringRunner.class)
@SpringBootTest(classes = GeneratorApp.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class UserTest {
	
	 
    @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
    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开发单元测试内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: SpringBoot使用@SpringBootTest注解开发单元测试教程

本文链接: https://www.lsjlt.com/news/129365.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作