gpt4 book ai didi

java - spring boot集成测试时如何正确连接testcontainers redis?

转载 作者:行者123 更新时间:2023-12-05 03:29:08 25 4
gpt4 key购买 nike

我正在为我的服务在 spring boot 中编写测试

@Component
public class MyService {
@Autowired
StringRedisTemplate stringRedisTemplate;
// a number of other @Autowired dependencies

public User getUser(String uuid) {
var key = String.format("user:%s", uuid);
var cache = stringRedisTemplate.opsForValue().get(key);
if (cache == null) {
// return user from database
} else {
// return user from deserialized cache
}
}
}

@Testcontainers
@SpringBootTest
class MyServiceTest {
@Autowired
StringRedisTemplate stringRedisTemplate;
@Autowired
MyService myService;

@Container
public static GenericContainer<?> redis =
new GenericContainer<>("redis:5.0.14-alpine3.15").withExposedPorts(6379);

@BeforeClass
public static void startContainer() {
redis.start();
var redisUrl = String.format("redis://%s:%s", redis.getHost(), redis.getMappedPort(6379));
System.setProperty("spring.redis.url", redisUrl);
}

@AfterClass
public static void stopContainer() {
redis.stop();
}

@Test
void getUser_returnCachedUser() {
// breakpoint here
stringRedisTemplate.opsForValue().set("user:some-uuid", "{\"uuid\":\"some-uuid\",\"name\":\"cache\"}");
var user = myService.getUser("some-uuid");
assertEquals("cache", user.name);
}
}

当我在 Debug模式下运行它并遇到断点时,我注意到控制台中的端口 redis.getMappedPort(6379) 不等于 stringRedisTemplate.connectionFactory.clientmyService.stringRedisTemplate.connectionFactory.client.

在这种情况下,System.setProperty 是否覆盖了属性并生效?如何在 Spring Boot 集成测试中使用测试容器?

最佳答案

我建议使用与 playtika 略有不同的容器它建立在测试容器之上。

你需要做的是包括spring-cloud-starter-bootstrap在您的 pom.xml 中(作为测试依赖项就足够了)。

然后在您的测试 application.yaml|properties 中使用以下内容:

spring:
redis:
port: ${embedded.redis.port}
password: ${embedded.redis.password}
host: ${embedded.redis.host}
ssl: false

关于java - spring boot集成测试时如何正确连接testcontainers redis?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71078017/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com