Spring Cloud 2.x系列之spring cloud如何使用spring-test进行单元测试
上篇和大家学习了spring cloud 如何整合reids,在测试时借用了web形式的restful接口进行的。那还有没有别的方式可以对spring boot和spring cloud编写的代码进行单元测试呢?答案:肯定是有的。这篇讲解一下如何使用spring-boot-starter-test进行单元测试
1、新建项目sc-test,对应的pom.xml文件如下
<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.0http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>spring-cloud</groupId> <artifactId>sc-test</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>sc-test</name> <url>http://maven.apache.org</url> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.4.RELEASE</version> </parent> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>Finchley.RELEASE</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> </dependency> <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> <scope>test</scope> </dependency> <!-- <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-test</artifactId> <scope>test</scope> </dependency>--> </dependencies> </project>
说明:只要使用spring-boot-starter-test即可,该jar已经包含spring-boot-test
2、新建spring boot启动类
package sc.test; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication publicclassTestApplication { publicstaticvoid main(String[] args) { SpringApplication.run(TestApplication.class, args); } }
备注:如果没有该类,spring-test启动将报错,见下图
3、新建操作redis的配置类
package sc.test.config; import java.io.Serializable; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer; @Configuration @AutoConfigureAfter(RedisAutoConfiguration.class) public class RedisCacheAutoConfiguration { @Bean public RedisTemplate<String, Serializable> redisCacheTemplate(LettuceConnectionFactory redisConnectionFactory) { RedisTemplate<String, Serializable> template = newRedisTemplate<>(); //键的序列化方式 template.setKeySerializer(new StringRedisSerializer()); //值的序列化方式 template.setValueSerializer(new GenericJackson2JsonRedisSerializer()); template.setConnectionFactory(redisConnectionFactory); return template; } }
4、新建配置文件application.yml
server: port: 9005 spring: application: name: sc-redis redis: host: 127.0.0.1 password: port: 6379 timeout: 10000 # 连接超时时间(毫秒) database: 0 # Redis默认情况下有16个分片,这里配置具体使用的分片,默认是0 lettuce: pool: max-active: 8 # 连接池最大连接数(使用负值表示没有限制)默认 8 max-wait: -1 # 连接池最大阻塞等待时间(使用负值表示没有限制)默认 -1 max-idle: 8 # 连接池中的最大空闲连接默认 8 min-idle: 0 # 连接池中的最小空闲连接默认 0
5、新建测试类TestRedis.java
package sc.test.unit; importjava.io.Serializable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.stream.IntStream; 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.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.test.context.junit4.SpringRunner; importsc.test.model.User; @RunWith(SpringRunner.class) @SpringBootTest publicclass TestRedis { private static final Logger log =LoggerFactory.getLogger(TestRedis.class); @Autowired private StringRedisTemplate stringRedisTemplate; @Autowired private RedisTemplate<String, Serializable> redisCacheTemplate; @Test public void get() { // 测试线程安全 // ExecutorServiceexecutorService = Executors.newFixedThreadPool(1000); // IntStream.range(0, 1000).forEach(i -> // executorService.execute(() ->stringRedisTemplate.opsForValue().increment("kk", 1)) // ); stringRedisTemplate.opsForValue().set("key", "{'name':'huangjinjin','age':30}"); final String value = stringRedisTemplate.opsForValue().get("key"); log.info("[字符缓存结果] - [{}]", value); String key = "manage:user:1"; User u = new User(); u.setId(1L); u.setAge(30); u.setPosition("cto"); u.setUserName("good boy"); redisCacheTemplate.opsForValue().set(key, u); //从缓存获取User对象 final User user = (User) redisCacheTemplate.opsForValue().get(key); log.info("[对象缓存结果] - userName={}, age={}, position={}", // user.getUserName(), user.getAge(), user.getPosition()); } }
6、进行测试
(1)reids server没有启动时,运行TestRedis.java(右键选择Junit Test)
连接不上Reids server异常
(2)reids server启动后时,运行TestRedis.java,出现绿条说明执行代码成功
日志中打印相关数据,说明数据也存贮到redisserver中
7、使用redis-cli验证数据是否正在存档redis server中
有了spring-boot-starter-test,就可以不使用restful接口对spring boot写的接口进行单元测试了。不但可以测试redis,也可以测试数据库的增删查改。可以使用spring中的各种注解,注入对象。
源码:
https://gitee.com/hjj520/spring-cloud-2.x/tree/master/sc-test
原文发布时间:2018-9-26
本文作者:java乐园
本文来自云栖社区合作伙伴“java乐园”,了解相关信息可以关注“java乐园”
低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。
持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。
转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。
- 上一篇
【死磕 Spring】----- IOC 之解析 bean 标签:解析自定义标签
前面四篇文章都是分析 Bean 默认标签的解析过程,包括基本属性、六个子元素(meta、lookup-method、replaced-method、constructor-arg、property、qualifier),涉及内容较多,拆分成了四篇文章,导致我们已经忘记从哪里出发的了, 勿忘初心。 processBeanDefinition() 负责 Bean 标签的解析,在解析过程中首先调用BeanDefinitionParserDelegate.parseBeanDefinitionElement() 完成默认标签的解析,如果解析成功(返回的 bdHolder != null ),则首先调用 BeanDefinitionParserDelegate.decorateBeanDefinitionIfRequired() 完成自定义标签元素解析,前面四篇文章已经分析了默认标签的解析,所以这篇文章分析自定义标签的解析。 public BeanDefinitionHolder decorateBeanDefinitionIfRequired(Element ele, BeanDefiniti...
- 下一篇
Bokeh中独特的数据类型简介: ColumnDataSource | Bokeh 小册子
Bokeh 系列文章传送门: Bokeh小册子:入门 Bokeh小册子:figure详细解读 29种Bokeh基础可视化图形,学会了可以大展身手…… | Bokeh 小册子 前面,我们分享了关于 bokeh 入门 、 figure 使用、以及bokeh基础图形介绍的内容。今天,我们在前文的基础上,主要来分享Bokeh中数据的使用方式,尤其是 Bokeh 特有的数据类型 ColumnDataSource 的使用。 本文主要内容如下: 1 直接提供数据 2 通过 ColumnDataSource 来提供数据 2.1 data 为字典 2.2 data 为 pandas 的 DataFrame 2.3 data 为 pandas 的 DataFrame 的 groupby 对象 本文的环境为 window 7 系统 python 3.6 Jupyter Notebook bokeh 0.13.0 数据是进行数据可视化的必要基础, 在 bokeh 中,数据有几种呈现方式。 (1)直接提供数据 (2)通过 ColumnDataSource 来提供数据 1 直接提供数据 首先加载相关Python库...
相关文章
文章评论
共有0条评论来说两句吧...
文章二维码
点击排行
-
Docker使用Oracle官方镜像安装(12C,18C,19C)
- Springboot2将连接池hikari替换为druid,体验最强大的数据库连接池
- CentOS8编译安装MySQL8.0.19
- Docker快速安装Oracle11G,搭建oracle11g学习环境
- SpringBoot2配置默认Tomcat设置,开启更多高级功能
- MySQL8.0.19开启GTID主从同步CentOS8
- CentOS7,8上快速安装Gitea,搭建Git服务器
- Jdk安装(Linux,MacOS,Windows),包含三大操作系统的最全安装
- SpringBoot2编写第一个Controller,响应你的http请求并返回结果
推荐阅读
最新文章
- SpringBoot2整合Redis,开启缓存,提高访问速度
- Jdk安装(Linux,MacOS,Windows),包含三大操作系统的最全安装
- SpringBoot2配置默认Tomcat设置,开启更多高级功能
- Springboot2将连接池hikari替换为druid,体验最强大的数据库连接池
- SpringBoot2整合MyBatis,连接MySql数据库做增删改查操作
- Hadoop3单机部署,实现最简伪集群
- Docker使用Oracle官方镜像安装(12C,18C,19C)
- MySQL8.0.19开启GTID主从同步CentOS8
- SpringBoot2编写第一个Controller,响应你的http请求并返回结果
- Windows10,CentOS7,CentOS8安装MongoDB4.0.16