首页 > 解决方案 > 使用 redis mock 进行 Redis 单元测试

问题描述

我正在使用以下工具运行嵌入式 redis 进行单元测试。

在我的registrationService的开始是创建一个redis服务器的新实例。

@Import({RedisConfiguration.class})
@Service
public class RegistrationService

RedisTemplate redisTemplate = new RedisTemplate();  //<- new instance

public String SubmitApplicationOverview(String OverviewRequest) throws IOException {

    . . .

    HashMap<String,Object> applicationData = mapper.readValue(OverviewRequest,new TypeReference<Map<String,Object>>(){});

    redisTemplate.setHashKeySerializer(new StringRedisSerializer());
    redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());

    UUID Key = UUID.randomUUID();

    redisTemplate.opsForHash().putAll(Key.toString(), (applicationData)); //<-- ERRORS HERE

    System.out.println("Application saved:" + OverviewRequest);

    return Key.toString();
 }
}

我在下面的测试中启动了一个模拟 redis 服务器。

...

RedisServer redisServer;

@Autowired
RegistrationService RegistrationService;

@Before
public void Setup() {
    redisServer = RedisServer.newRedisServer();
    redisServer.start();
}

@Test
public void testSubmitApplicationOverview() {
    String body = "{\n" +
            "    \"VehicleCategory\": \"CAR\",\n" +
            "    \"EmailAddress\": \"email@email.com\"\n" +
            "}";
    String result = RegistrationService.SubmitApplicationOverview(body);

    Assert.assertEquals("something", result);
}

application.properties中的 Redis 设置

#Redis Settings
spring.redis.cluster.nodes=slave0:6379,slave1:6379
spring.redis.url= redis://jx-staging-redis-ha-master-svc.jx-staging:6379
spring.redis.sentinel.master=mymaster
spring.redis.sentinel.nodes=10.40.2.126:26379,10.40.1.65:26379
spring.redis.database=2

但是,我在测试中的服务 (registrationService) 中java.lang.NullPointerException 的以下行出现错误。

redisTemplate.opsForHash().putAll(Key.toString(), (applicationData));

标签: unit-testingredis

解决方案


根据[redis-mock][1]文档,创建一个这样的实例:

RedisServer.newRedisServer();  // bind to a random port

将实例绑定到随机端口。看起来您的代码需要一个特定的端口。我相信您需要在创建服务器时通过传递这样的端口号来指定一个端口:

RedisServer.newRedisServer(8000);  // bind to a specific port

推荐阅读