spring boot单元测试之十:用embedded-redis库做Redis的mock(spring boot 2.4.3)

一,演示项目的相关信息

1,地址:

https://github.com/liuhongdi/redismock

2,功能说明:演示用embedded-redis做redis的测试

3,项目结构:如图:

说明:刘宏缔的架构森林是一个专注架构的博客,地址:https://www.cnblogs.com/architectforest

         对应的源码可以访问这里获取: https://github.com/liuhongdi/

说明:作者:刘宏缔 邮箱: 371125307@qq.com

二,配置文件

1,pom.xml

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!--redis begin-->
        <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>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.11.1</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.11.1</version>
        </dependency>
        <!--redis   end-->

        <!--redis test begin-->
        <dependency>
            <groupId>it.ozimov</groupId>
            <artifactId>embedded-redis</artifactId>
            <version>0.7.3</version>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-simple</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!--redis test   end-->

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

2,application-dev.yml

#redis1
spring:
  redis1:
    enabled: 1
    host: localhost
    port: 6379
    password:
    database: 15
    lettuce:
      pool:
        max-active: 32
        max-wait: 300
        max-idle: 16
        min-idle: 8

三,java代码

1,config/RedisConfig.java

@Configuration
public class RedisConfig {

    @Bean
    @Primary
    public LettuceConnectionFactory redis1LettuceConnectionFactory(RedisStandaloneConfiguration redis1RedisConfig,
                                                                    GenericObjectPoolConfig redis1PoolConfig) {
        LettuceClientConfiguration clientConfig =
                LettucePoolingClientConfiguration.builder().commandTimeout(Duration.ofMillis(100))
                        .poolConfig(redis1PoolConfig).build();
        return new LettuceConnectionFactory(redis1RedisConfig, clientConfig);
    }

    @Bean
    public RedisTemplate<String, String> redis1Template(
            @Qualifier("redis1LettuceConnectionFactory") LettuceConnectionFactory redis1LettuceConnectionFactory) {
        RedisTemplate<String, String> redisTemplate = new RedisTemplate<>();
        //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        //使用StringRedisSerializer来序列化和反序列化redis的key值
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
        //开启事务
        redisTemplate.setEnableTransactionSupport(true);
        redisTemplate.setConnectionFactory(redis1LettuceConnectionFactory);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

    @Configuration
    public static class Redis1Config {
        @Value("${spring.redis1.host}")
        private String host;
        @Value("${spring.redis1.port}")
        private Integer port;
        @Value("${spring.redis1.password}")
        private String password;
        @Value("${spring.redis1.database}")
        private Integer database;

        @Value("${spring.redis1.lettuce.pool.max-active}")
        private Integer maxActive;
        @Value("${spring.redis1.lettuce.pool.max-idle}")
        private Integer maxIdle;
        @Value("${spring.redis1.lettuce.pool.max-wait}")
        private Long maxWait;
        @Value("${spring.redis1.lettuce.pool.min-idle}")
        private Integer minIdle;

        @Bean
        public GenericObjectPoolConfig redis1PoolConfig() {
            GenericObjectPoolConfig config = new GenericObjectPoolConfig();
            config.setMaxTotal(maxActive);
            config.setMaxIdle(maxIdle);
            config.setMinIdle(minIdle);
            config.setMaxWaitMillis(maxWait);
            return config;
        }

        @Bean
        public RedisStandaloneConfiguration redis1RedisConfig() {
            RedisStandaloneConfiguration config = new RedisStandaloneConfiguration();
            config.setHostName(host);
            config.setPassword(RedisPassword.of(password));
            config.setPort(port);
            config.setDatabase(database);
            return config;
        }
    }
}

2,pojo/Goods.java

public class Goods {
    //商品id
    Long goodsId;
    public Long getGoodsId() {
        return this.goodsId;
    }
    public void setGoodsId(Long goodsId) {
        this.goodsId = goodsId;
    }

    //商品名称
    private String goodsName;
    public String getGoodsName() {
        return this.goodsName;
    }
    public void setGoodsName(String goodsName) {
        this.goodsName = goodsName;
    }

    @Override
    public String toString(){
        return " Goods:goodsId=" + goodsId +" goodsName=" + goodsName;
    }
}

3,impl/GoodsServiceImpl.java

@Service
public class GoodsServiceImpl implements GoodsService {

    @Resource
    private RedisTemplate redis1Template;

    //得到一件商品的信息
    @Override
    public Goods getOneGoodsById(Long goodsId) {
        Goods goodsOne;

            System.out.println("get data from redis");
            Object goodsr = redis1Template.opsForValue().get("goods_"+String.valueOf(goodsId));
            if (goodsr == null) {
                goodsOne = null;
            } else {
                if (goodsr.equals("-1")) {
                    goodsOne = null;
                } else {
                    goodsOne = (Goods)goodsr;
                }
            }
        return goodsOne;
    }

    @Override
    public void setOneGoods(Goods goods){
        redis1Template.opsForValue().set("goods_"+String.valueOf(goods.getGoodsId()),goods,600, TimeUnit.SECONDS);
    }
}

4,impl/GoodsServiceImplTest.java

import static org.junit.jupiter.api.Assertions.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import com.jayway.jsonpath.JsonPath;


@SpringBootTest
class GoodsServiceImplTest {

    @Resource
    private RedisTemplate redisTemplate;

    @Autowired
    private GoodsService goodsService;

    private static RedisServer redisServer;


    @BeforeAll
    static void startRedis() {
        redisServer = RedisServer.builder()
                .port(6379)
                .setting("maxmemory 128M") //maxheap 128M
                .build();
        redisServer.start();
    }

    /**
     * 析构方法之后执行,停止Redis.
     */
    @AfterAll
    static void stopRedis() {
        redisServer.stop();
    }

    @Test
    @DisplayName("测试从嵌入redis写入并读取数据")
    void getOneGoodsById() {
        Goods gset = new Goods();
        gset.setGoodsId(5L);
        gset.setGoodsName("test5");
        goodsService.setOneGoods(gset);

        Goods goods = goodsService.getOneGoodsById(5L);
        System.out.println(goods);
        assertThat(goods.getGoodsId(), equalTo(5L));
        assertThat(goods.getGoodsName(), equalTo("test5"));
    }

}

5, 其他相关代码可访问github

四,测试效果

五,查看spring boot版本:

  .   ____          _            __ _ _
 /\ / ___'_ __ _ _(_)_ __  __ _    
( ( )\___ | '_ | '_| | '_ / _` |    
 \/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.4.3)
原文地址:https://www.cnblogs.com/architectforest/p/14596556.html