使用Redis模拟进行Redis单元测试

4
我正在使用这个工具运行内嵌的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));
1个回答

1
根据[redis-mock][1]文档,创建以下实例:

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

将实例绑定到随机端口。看起来你的代码期望一个特定的端口。我认为在创建服务器时需要指定一个端口,像这样传递一个端口号:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接