Spring Cloud 2.x系列之spring cloud如何使用spring-test进行单元测试

本文涉及的产品
Redis 开源版,标准版 2GB
推荐场景:
搭建游戏排行榜
云数据库 Tair(兼容Redis),内存型 2GB
简介: 上篇和大家学习了spring cloud 如何整合reids,在测试时借用了web形式的restful接口进行的。那还有没有别的方式可以对spring boot和spring cloud编写的代码进行单元测试呢?答案:肯定是有的。

上篇和大家学习了spring cloud 如何整合reids,在测试时借用了web形式的restful接口进行的。那还有没有别的方式可以对spring boot和spring 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.0http://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

5326c31d54685e035c8a88ae022daad4439197bd

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

a4b57dbd7a0811c04c6e3fbc062980b0554389a8

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 = 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<String, Serializable> 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)

c2d00c2ad685d7e210f7b7038b801f1d07d54f70

连接不上Reids server异常

 1f2dea9c7f03d74770fff20d9717770ee73e7b42

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

fc6d60da256cd4d1c28e6d03628833abb1f9ea0a

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

af9c9456befdd6d56691bdbd75d35a1e4822c981

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

68583a901319281fc4ba2a2dc97aec0fb5a7b12d

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

源码:

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

原文发布时间:2018-9-26

本文作者:java乐园

本文来自云栖社区合作伙伴“java乐园”,了解相关信息可以关注“java乐园


相关文章
|
4月前
|
人工智能 Java 测试技术
Spring Boot 集成 JUnit 单元测试
本文介绍了在Spring Boot中使用JUnit 5进行单元测试的常用方法与技巧,包括添加依赖、编写测试类、使用@SpringBootTest参数、自动装配测试模块(如JSON、MVC、WebFlux、JDBC等),以及@MockBean和@SpyBean的应用。内容实用,适合Java开发者参考学习。
467 0
|
3月前
|
Java 测试技术 Spring
简单学Spring Boot | 博客项目的测试
本内容介绍了基于Spring Boot的博客项目测试实践,重点在于通过测试驱动开发(TDD)优化服务层代码,提升代码质量和功能可靠性。案例详细展示了如何为PostService类编写测试用例、运行测试并根据反馈优化功能代码,包括两次优化过程。通过TDD流程,确保每项功能经过严格验证,增强代码可维护性与系统稳定性。
164 0
|
4月前
|
安全 Java 测试技术
说一说 Spring Security 中的单元测试
我是小假 期待与你的下一次相遇 ~
|
7月前
|
负载均衡 Dubbo Java
Spring Cloud Alibaba与Spring Cloud区别和联系?
Spring Cloud Alibaba与Spring Cloud区别和联系?
|
8月前
|
前端开发 Java Nacos
🛡️Spring Boot 3 整合 Spring Cloud Gateway 工程实践
本文介绍了如何使用Spring Cloud Alibaba 2023.0.0.0技术栈构建微服务网关,以应对微服务架构中流量治理与安全管控的复杂性。通过一个包含鉴权服务、文件服务和主服务的项目,详细讲解了网关的整合与功能开发。首先,通过统一路由配置,将所有请求集中到网关进行管理;其次,实现了限流防刷功能,防止恶意刷接口;最后,添加了登录鉴权机制,确保用户身份验证。整个过程结合Nacos注册中心,确保服务注册与配置管理的高效性。通过这些实践,帮助开发者更好地理解和应用微服务网关。
1312 0
🛡️Spring Boot 3 整合 Spring Cloud Gateway 工程实践
|
9月前
|
人工智能 安全 Java
AI 时代:从 Spring Cloud Alibaba 到 Spring AI Alibaba
本次分享由阿里云智能集团云原生微服务技术负责人李艳林主讲,主题为“AI时代:从Spring Cloud Alibaba到Spring AI Alibaba”。内容涵盖应用架构演进、AI agent框架发展趋势及Spring AI Alibaba的重磅发布。分享介绍了AI原生架构与传统架构的融合,强调了API优先、事件驱动和AI运维的重要性。同时,详细解析了Spring AI Alibaba的三层抽象设计,包括模型支持、工作流智能体编排及生产可用性构建能力,确保安全合规、高效部署与可观测性。最后,结合实际案例展示了如何利用私域数据优化AI应用,提升业务价值。
805 4
|
9月前
|
Java 测试技术 应用服务中间件
Spring Boot 如何测试打包部署
本文介绍了 Spring Boot 项目的开发、调试、打包及投产上线的全流程。主要内容包括: 1. **单元测试**:通过添加 `spring-boot-starter-test` 包,使用 `@RunWith(SpringRunner.class)` 和 `@SpringBootTest` 注解进行测试类开发。 2. **集成测试**:支持热部署,通过添加 `spring-boot-devtools` 实现代码修改后自动重启。 3. **投产上线**:提供两种部署方案,一是打包成 jar 包直接运行,二是打包成 war 包部署到 Tomcat 服务器。
210 10
|
10月前
|
消息中间件 监控 Java
如何将Spring Boot + RabbitMQ应用程序部署到Pivotal Cloud Foundry (PCF)
如何将Spring Boot + RabbitMQ应用程序部署到Pivotal Cloud Foundry (PCF)
154 6
|
10月前
|
负载均衡 Java 开发者
深入探索Spring Cloud与Spring Boot:构建微服务架构的实践经验
深入探索Spring Cloud与Spring Boot:构建微服务架构的实践经验
539 5
|
10月前
|
Java 关系型数据库 MySQL
如何将Spring Boot + MySQL应用程序部署到Pivotal Cloud Foundry (PCF)
如何将Spring Boot + MySQL应用程序部署到Pivotal Cloud Foundry (PCF)
168 5