java测试spring cloud_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文件如下

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0http://maven.apache.org/xsd/maven-4.0.0.xsd">

4.0.0

spring-cloud

sc-test

0.0.1-SNAPSHOT

jar

sc-test

http://maven.apache.org

org.springframework.boot

spring-boot-starter-parent

2.0.4.RELEASE

org.springframework.cloud

spring-cloud-dependencies

Finchley.RELEASE

pom

import

UTF-8

1.8

1.8

org.springframework.boot

spring-boot-starter-data-redis

org.apache.commons

commons-pool2

org.springframework.boot

spring-boot-starter-web

org.springframework.boot

spring-boot-starter-test

test

说明:只要使用spring-boot-starter-test即可,该jar已经包含spring-boot-test

628dfe3b4173cc811160693ffc7285b0.png

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启动将报错,见下图

e5ea494f0a016911f75aa40b4efc49d2.png

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 redisCacheTemplate(LettuceConnectionFactory redisConnectionFactory) {

RedisTemplate 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 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)

ca3c2ca319204b54e8425428708bb8ee.png

连接不上Reids server异常

3667816c7e966820fe55e98ad43a8bb3.png

(2)reids server启动后时,运行TestRedis.java,出现绿条说明执行代码成功

77e202900cb9a15fd1f1ada886cd3487.png

日志中打印相关数据,说明数据也存贮到redisserver中

1e243edf5609b0129b1dd4b8b5602d92.png

7、使用redis-cli验证数据是否正在存档redis server中

69f26d6aed9cc56e0e498f7ad5e24670.png

有了spring-boot-starter-test,就可以不使用restful接口对spring boot写的接口进行单元测试了。不但可以测试redis,也可以测试数据库的增删查改。可以使用spring中的各种注解,注入对象。

源码:

https://gitee.com/hjj520/spring-cloud-2.x/tree/master/sc-test

本公众号内回复 “领取资源”, 下载各种编程资料;

觉得本文对你有帮助?请分享给更多人

关注「JAVA乐园」,提升IT技能

062f0aff41fbcaacd2a50ac7686f1cd0.gif

推荐阅读:

更多精彩文章,请点击下方:阅读原文

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值