詳解spring cloud如何使用spring-test進(jìn)行單元測試
上篇和大家學(xué)習(xí)了spring cloud 如何整合reids,在測試時借用了web形式的restful接口進(jìn)行的。那還有沒有別的方式可以對spring boot和spring cloud編寫的代碼進(jìn)行單元測試呢?答案:肯定是有的。這篇講解一下如何使用 spring-boot-starter-test進(jìn)行單元測試
1、新建項目sc-test,對應(yīng)的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.0 http://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已經(jīng)包含spring-boot-test

2、新建spring boot啟動類
package sc.test;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class TestApplication {
public static void 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 = new RedisTemplate<>();
//鍵的序列化方式
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默認(rèn)情況下有16個分片,這里配置具體使用的分片,默認(rèn)是0
lettuce:
pool:
max-active: 8 # 連接池最大連接數(shù)(使用負(fù)值表示沒有限制) 默認(rèn) 8
max-wait: -1 # 連接池最大阻塞等待時間(使用負(fù)值表示沒有限制) 默認(rèn) -1
max-idle: 8 # 連接池中的最大空閑連接 默認(rèn) 8
min-idle: 0 # 連接池中的最小空閑連接 默認(rèn) 0
5、新建測試類TestRedis.java
package sc.test.unit;
import java.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;
import sc.test.model.User;
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestRedis {
private static final Logger log = LoggerFactory.getLogger(TestRedis.class);
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Autowired
private RedisTemplate<String, Serializable> redisCacheTemplate;
@Test
public void get() {
// 測試線程安全
// ExecutorService executorService = 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("[字符緩存結(jié)果] - [{}]", 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("[對象緩存結(jié)果] - userName={}, age={}, position={}", //
user.getUserName(), user.getAge(), user.getPosition());
}
}
6、進(jìn)行測試
(1)reids server沒有啟動時,運(yùn)行TestRedis.java(右鍵選擇Junit Test)

連接不上Reids server異常

(2)reids server啟動后時,運(yùn)行TestRedis.java,出現(xiàn)綠條說明執(zhí)行代碼成功

日志中打印相關(guān)數(shù)據(jù),說明數(shù)據(jù)也存貯到redis server中

7、使用redis-cli驗證數(shù)據(jù)是否正在存檔redis server中

有了spring-boot-starter-test,就可以不使用restful接口對spring boot寫的接口進(jìn)行單元測試了。不但可以測試redis,也可以測試數(shù)據(jù)庫的增刪查改。可以使用spring中的各種注解,注入對象。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Java實現(xiàn)List集合轉(zhuǎn)樹形結(jié)構(gòu)的示例詳解
在開發(fā)中,我們通常需要將從數(shù)據(jù)庫中查詢的集合數(shù)據(jù)轉(zhuǎn)換成類似文件系統(tǒng)一樣的樹形集合。本文將利用Java語言實現(xiàn)這一功能,感興趣的可以了解一下2022-08-08
Mybatis Generator最完美配置文件詳解(完整版)
今天小編給大家整理了一篇關(guān)于Mybatis Generator最完美配置文件詳解教程,非常不錯具有參考借鑒價值,感興趣的朋友一起學(xué)習(xí)吧2016-11-11
深度剖析Java成員變量、局部變量和靜態(tài)變量的創(chuàng)建和回收時機(jī)
這篇文章主要介紹了深度剖析Java成員變量、局部變量和靜態(tài)變量的創(chuàng)建和回收時機(jī),成員變量是定義在類中的變量,每個類的實例都會擁有自己的成員變量。它們的生命周期與對象的創(chuàng)建和銷毀相對應(yīng),下面我將詳細(xì)介紹它們的特點(diǎn)和生命周期,需要的朋友可以參考下2023-07-07
聊聊SpringCloud中的Ribbon進(jìn)行服務(wù)調(diào)用的問題
SpringCloud-Ribbon是基于Netflix?Ribbon實現(xiàn)的一套客戶端負(fù)載均衡的工具。本文給大家介紹SpringCloud中的Ribbon進(jìn)行服務(wù)調(diào)用的問題,感興趣的朋友跟隨小編一起看看吧2022-01-01
springboot動態(tài)調(diào)整日志級別的操作大全
這篇文章主要介紹了springboot動態(tài)調(diào)整日志級別的方法,本文通過實例圖文相結(jié)合給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-10-10

