unit-testing - 使用 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));
解决方案
根据[redis-mock][1]
文档,创建一个这样的实例:
RedisServer.newRedisServer(); // bind to a random port
将实例绑定到随机端口。看起来您的代码需要一个特定的端口。我相信您需要在创建服务器时通过传递这样的端口号来指定一个端口:
RedisServer.newRedisServer(8000); // bind to a specific port
推荐阅读
- powerbi - 返回每个组每个帐户的第一个非空白日期 - Power BI
- java - 如何使用 volley 将 Body 数据发送到 GET Method Request android?
- java - 我正在尝试为 jolt 变换制作一个 json,但我被困在嵌套数组格式中
- javascript - 将 BODMAS 应用于 Javascript 函数
- reactjs - 如何扩展和覆盖样式对象reactjs
- linux - 在终端上记录操作
- javascript - 'gulp-babel' 在节点 js 版本 4 中不起作用
- laravel - Laravel - 如何在 Eloquent Top 5 查询中添加 where 子句
- javascript - 我有对象数组,我的目标是仅使用 forEach 按升序打印对象的年龄
- vb.net - 通过 webrequest vb.net 获取 JSON 数据