使用SpringBootTest和嵌入式Redis
简而言之
-
- Redisを使用しているSpringBootアプリケーションのテストを実装していたのだが、テストは「完全にlocalで実行できるべし」が信条なのでサーバーに構築したRedisにはアクセスしたくない…
- そんなときに組み込みRedisが使えそうだということを知ったので、まとめてみました
请先总结一下。
it.ozimov:embedded-redisというライブラリを使う
RedisServer#startにより組み込みRedisを起動する
使用库
Note: The translation provided is in Simplified Chinese.
ライブラリバージョンorg.springframework.boot:spring-boot-starter-data-redis2.3.5.RELEASEorg.springframework.boot:spring-boot-starter-test2.3.5.RELEASEit.ozimov:embedded-redis0.7.2
示例应用的实现
首先是关于依赖关系的事项。 it.ozimov:embedded-redis是使用嵌入式Redis所需的库。
plugins {
id 'org.springframework.boot' version '2.3.5.RELEASE'
id 'io.spring.dependency-management' version '1.0.10.RELEASE'
id 'java'
}
sourceCompatibility = 11
targetCompatibility = 11
test {
useJUnitPlatform()
}
repositories {
mavenCentral()
maven {
url "http://maven.springframework.org/milestone"
}
maven { url 'https://repo.spring.io/milestone' }
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-data-redis'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'it.ozimov:embedded-redis:0.7.2'
}
通过先调用样例API中的/set,然后再调用/get,应该会返回一个名为value的字符串。
@RequiredArgsConstructor
@RestController
public class SampleController {
private final RedisTemplate<String, String> redisTemplate;
@GetMapping("/set")
public void set() {
redisTemplate.opsForValue().set("key", "value");
}
@GetMapping("/get")
public String get() {
return redisTemplate.opsForValue().get("key");
}
}
下面是设置方面的内容。请明确指出默认设置。
spring:
redis:
host: localhost
port: 6379
测试的实施
为了使用内嵌的Redis,我们准备了一个用于测试的配置类。
@TestConfiguration
@EnableConfigurationProperties(RedisProperties.class)
public class RedisTestAutoConfiguration {
private static RedisServer redisServer = null;
/**
* constructor
*/
public RedisAutoConfiguration(RedisProperties redisProperties) {
// サーバーを起動
start(redisProperties);
}
public static synchronized void start(RedisProperties redisProperties) {
if (redisServer == null) {
redisServer = new RedisServer(redisProperties.getPort());
redisServer.start();
}
}
@PreDestroy
public void preDestroy() {
// サーバを停止
stop();
}
public static synchronized void stop() {
if (redisServer != null) {
redisServer.stop();
redisServer = null;
}
}
}
RedisProperties是Spring Boot提供的与Redis相关的ConfigurationProperty类。
您可以指定端口来创建RedisServer,并使用start方法启动它。
最后是测试类!
@ExtendWith(SpringExtension.class)
@SpringBootTest(
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
classes = RedisTestAutoConfiguration.class)
class ApplicationTest {
@Autowired
private TestRestTemplate restTemplate;
@Test
void test() {
restTemplate.getForObject("/set", Void.class);
var value = restTemplate.getForObject("/get", String.class);
assertThat(value).isEqualTo("value");
}
}
您可以通过在@SpringBootTest中指定先前实现的RedisTestAutoConfiguration来使用内嵌的Redis服务器!
※もちろんこの指定がないと、localにRedisを立てない限りテストが通りません?
可以参考
- https://www.baeldung.com/spring-embedded-redis