目录

SpringCloud使用spring-test进行单元测试教程

步骤

1、 新建项目sc-test,对应的pom.xml文件如下

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<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 ./1.png

2、 新建spring boot启动类

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
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启动将报错,见下图

./2.png

3、 新建操作redis的配置类

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
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)

./3.png

接不上Reids server异常

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

./5.png

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

./6.png

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

./7.png

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

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