18. How spring cloud uses spring test for unit test

Keywords: Programming Spring Redis Java Maven

Love official account: java paradise

In the last part, I learned how spring cloud integrates reids and borrowed the restful interface in the form of web for testing. Is there any other way to unit test the code written by spring boot and spring cloud? Answer: there must be. This article explains how to use spring boot starter test for unit test

1. Create a new project SC test, and the corresponding pom.xml file is as follows

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

Note: just use spring boot starter test. The jar already contains spring boot test

2. New spring boot class

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);
    }

}

Note: if there is no such class, the spring test startup will report an error, as shown in the following figure

3. Create a configuration class for 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<>();
                //Serialization of keys
                template.setKeySerializer(new StringRedisSerializer());
                //Serialization of values
                template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
                template.setConnectionFactory(redisConnectionFactory);
                return template;
        }
}

4. New configuration file application.yml

server:
    port: 9005

spring:
    application:
        name: sc-redis
    redis:
        host: 127.0.0.1
        password: 
        port: 6379
        timeout: 10000 # Connection timeout (MS)
        database: 0 # Redis has 16 partitions by default. The specific partition is configured here. The default is 0
        lettuce:
            pool:
                max-active: 8 # Connection pool maximum connections (negative for no limit) default 8
                max-wait: -1 # Connection pool maximum block wait time (use a negative value to indicate no limit) default - 1
                max-idle: 8 # Maximum idle connections in connection pool default 8
                min-idle: 0 # Minimum free connections in connection pool default 0

5. New test class 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() {
                // Test thread safety
//        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("[Character cache results] - [{}]", 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);
                //Get User object from cache
                final User user = (User) redisCacheTemplate.opsForValue().get(key);
                log.info("[Object cache results] - userName={}, age={}, position={}", //
                        user.getUserName(), user.getAge(), user.getPosition());
        }
}

6. Conduct the test
(1) When the reids server is not started, run TestRedis.java (right click to select Junit Test)

Unable to connect to Reids server exception

(2) When the reids server is started, run TestRedis.java, and a green bar appears indicating that the code is executed successfully

Print the relevant data in the log, indicating that the data is also stored in the redis server

7. Using redis cli to verify whether data is being archived in redis server

With spring boot starter test, you can unit test the interface written by spring boot without using restful interface. You can test not only redis, but also the addition, deletion, query and modification of the database. You can inject objects using various annotations in spring.

Posted by mmponline on Mon, 04 May 2020 20:05:03 -0700