18、spring cloud如何使用spring-test進行單元測試


 

上篇和大家學習了spring cloud 如何整合reids,在測試時借用了web形式的restful接口進行的。那還有沒有別的方式可以對spring bootspring 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.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已經包含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默認情況下有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;

 

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("[字符緩存結果] - [{}]", 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,出現綠條說明執行代碼成功

 

 

 

日志中打印相關數據,說明數據也存貯到redis server

 

 

 

7、 使用redis-cli驗證數據是否正在存檔redis server

 

 

 

有了spring-boot-starter-test,就可以不使用restful接口對spring boot寫的接口進行單元測試了。不但可以測試redis,也可以測試數據庫的增刪查改。可以使用spring中的各種注解,注入對象。

 

https://gitee.com/hjj520/spring-cloud-2.x


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM