设计到Redis的单元测试是比较麻烦的,一般使用embeded-redis或redis-mock。因为embeded-redis启动会失败,而且没有看到错误日志(只有
Can't start redis server. Check logs for details
),所以最后选择了redis-mock。
添加依赖pom.xml
添加依赖项:redis-mock
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>ai.grakn</groupId>
<artifactId>redis-mock</artifactId>
<version>0.1.6</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
Redis使用代码RedisTestApplication.java
@SpringBootApplication
public class RedisTestApplication {
@Resource
private StringRedisTemplate stringRedisTemplate;
public static void main(String[] args) {
SpringApplication.run(RedisTestApplication.class, args);
}
@Bean
public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
return args -> {
stringRedisTemplate.opsForValue().set("name", "tenmao");
String name = stringRedisTemplate.opsForValue().get("name");
System.out.println(name);
};
}
}
Redis测试代码
@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisTestApplicationTests {
@Resource
private StringRedisTemplate stringRedisTemplate;
private static RedisServer redisServer = null;
@BeforeClass
public static void init() {
try {
redisServer = RedisServer.newRedisServer();
redisServer.start();
//因为RedisServer启动的端口无法预知(如果写死的话就容易有端口冲突),所以需要实现动态端口配置。
System.setProperty("spring.redis.port", Integer.toString(redisServer.getBindPort()));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@AfterClass
public static void close() {
if (redisServer != null) {
redisServer.stop();
}
}
@Test
public void testRedis() {
String name = stringRedisTemplate.opsForValue().get("name");
Assert.assertEquals("tenmao", name);
}
}
网友评论