【问题标题】:Redis unit test using redis mock使用 redis mock 进行 Redis 单元测试
【发布时间】:2020-10-29 16:55:25
【问题描述】:

我正在使用following 工具运行嵌入式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-testing redis


    【解决方案1】:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 2020-10-19
      • 1970-01-01
      • 1970-01-01
      • 2013-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多