如何将SpringBootTest和Testcontainers与伪造的gcs服务器容器相结合



我正在尝试编写一个测试用例,用于使用Spring Boot(v2.7.5(测试对Google Cloud Bucket的读写访问。为此,我尝试将"Testcontainer"框架与伪造的Google Cloud Storage容器(伪造的gcs服务器(结合使用。

问题是应用程序没有以此配置启动。错误消息是";应用程序默认凭据不可用">

我已经设置了".setCredentials(NoCredentials.getInstance(((",但这没有帮助。

@SpringBootTest
@TestInstance(TestInstance.Lifecycle.PER_CLASS) // Share data between the test methods
@TestMethodOrder(MethodOrderer.OrderAnnotation.class) // Enable ordering of test methods
@Testcontainers
class GPSStorageTest {
private static final String BUCKET_NAME = "BUCKET_TEST";
private static final Integer INTERNAL_PORT = 8888;
protected static Storage storage = null;
// Set the GenericContainer to 'static' and the GenericContainer will be shared between test methods
@Container
private static final GenericContainer<?>gcsFakeContainer =
new GenericContainer<>(DockerImageName.parse("fsouza/fake-gcs-server:latest"))
.withCommand("-port",INTERNAL_PORT.toString(), "-scheme", "http")
.withExposedPorts(8888)
.waitingFor(Wait.forHttp("/").forStatusCode(404))
.withReuse(true);
@BeforeAll
public static void setup() {
int mappedPort = gcsFakeContainer.getMappedPort(INTERNAL_PORT);
StorageOptions storageOps = StorageOptions.newBuilder()
.setCredentials(NoCredentials.getInstance())
.setHost("http://" + gcsFakeContainer.getHost() + ":" + mappedPort)
.setProjectId("TEST_LOCAL")
.build();
storage = storageOps.getService();
}
@Test
@Order(1)
public void testCreateBucket() {
createBucket();
Assertions.assertTrue(checkBucketExists());
}
@Test
@Order(2)
public void testIfFileWritten() {
String filename = "test.txt";
Bucket bucket = storage.get(BUCKET_NAME);
bucket.create(filename, "Hello, World!".getBytes(UTF_8));
Assertions.assertTrue(fileExits(filename));
}
private boolean fileExits(String filename) {
return storage.get(BUCKET_NAME,filename) != null;
}
private void createBucket() {
try {
storage.create(BucketInfo.of(BUCKET_NAME));
} catch (Exception ex) {
System.err.println("Error creating bucket");
ex.printStackTrace();
}
}
private boolean checkBucketExists() {
return storage.get(BUCKET_NAME, Storage.BucketGetOption.fields()) != null;
}
}

有人对我如何让它发挥作用有什么想法吗?

更新我把上一个类放在一个小的演示项目中来演示这个问题:https://github.com/benocms/de.test.testcontainers

我解决了这个问题。

此配置禁用cloud.gcp.storage API的自动Spring Boot配置。

application.properties:

spring.cloud.gcp.storage.enabled=false

更新

这种配置在测试类本身中也是可能的:

@DynamicPropertySource
static void gcsFakeProperties(DynamicPropertyRegistry registry) {
registry.add("spring.cloud.gcp.storage.enabled",()-> false);
}

注意:@DynamicPropertySource注释仅在Spring Boot>=之后可用2.2.6.

最新更新