Implement Testcontainers GCloud Module With Spring Boot for Writing Integration Tests
This article explains how to write integration tests using the Testcontainers GCloud module for the Spanner database using Spring Boot.
Join the DZone community and get the full member experience.
Join For FreeTestcontainers is a library that is helpful with writing reliable integration tests in a module-specific (Databases, Kafka, Redis) Docker container. Once the execution of tests is over, the containers are destroyed completely.
If your application is using Google Cloud components like Spanner, Firestore, etc. to write efficient integration tests, Testcontainers offers a GCloud module for Google Cloud Platform’s Cloud SDK.
This article explains how to write integration tests using the Testcontainers GCloud module for the Spanner database using Spring Boot.
What Is an Emulator?
An emulator is designed to run on the local/offline environment, and it emulates the behavior of a cloud service like Spanner. It is used for testing locally without connecting to the cloud environment.
What Is Testcontainers GCloud Module?
The GCloud module helps in easily spinning up Google Cloud emulators for services like Pub/Sub and Spanner. As per the Testcontainers documentation, the GCloud module (as of now) supports Bigtable, Datastore, Firestore, Spanner, and Pub/Sub emulators. We can assume the GCloud API is a wrapper over the Cloud SDK emulator and Docker.
Integration Test
Consider a demo order service written in Spring Boot that is used to place an order. The orders are stored in a Spanner database table called "Orders." Refer to the spanner-testcontainers-demo sample service code.
For writing the integration tests using Testcontainers, GCloud, and Junit5, first, we need to import the following libraries in "build.gradle."
//TestContainers
testImplementation 'org.testcontainers:testcontainers:1.17.3'
testImplementation group: 'org.testcontainers', name: 'junit-jupiter', version: '1.17.3'
testImplementation group: 'org.junit.jupiter', name: 'junit-jupiter-api', version: '5.9.0'
implementation 'org.testcontainers:gcloud:1.17.3'
The next step is to spin up the Spanner Emulator using the SpannerEmulatorContainer
instance.
@Container
private static final SpannerEmulatorContainer spannerEmulatorContainer =
new SpannerEmulatorContainer(
DockerImageName.parse("gcr.io/cloud-spanner-emulator/emulator:1.1.1"));
SpannerEmulatorContainer
is declared static because then a single container is started and it is shared across all the test methods.
@DynamicPropertySource
is used for overriding the properties. Just as we do for MySQLContainer and PostgresContainer, we let Testcontainers create the URL, username, and password to avoid errors. Similarly, in the case of Spanner, we let Testcontainers create the emulator host for us.
@DynamicPropertySource
static void emulatorProperties(DynamicPropertyRegistry registry) {
registry.add(
"spring.cloud.gcp.spanner.emulator-host", spannerEmulatorContainer::getEmulatorGrpcEndpoint);
}
On local, if we run the Spring Boot application and missed configuring the cloud “service account” key or credentials, we end up getting the following:
The Application Default Credentials are not available.
They are available if running in Google Compute Engine.
Otherwise, the environment variable GOOGLE_APPLICATION_CREDENTIALS must be defined pointing to a file defining the credentials
To avoid this error in our tests, we need to define NoCredentialsProvider
. This is because, for testing, there is no need to use credentials: let Bootstrap use the NoCredentialsProvider
instance.
@TestConfiguration
static class EmulatorConfiguration {
@Bean
NoCredentialsProvider googleCredentials() {
return NoCredentialsProvider.create();
}
}
This is the basic configuration required for setting up the SpannerEmulatorContainer
. The next step is to create a Spanner instance, database, and table.
private InstanceId createInstance(Spanner spanner) throws InterruptedException, ExecutionException {
InstanceConfigId instanceConfig = InstanceConfigId.of(PROJECT_ID, "emulator-config");
InstanceId instanceId = InstanceId.of(PROJECT_ID, INSTANCE_ID);
InstanceAdminClient insAdminClient = spanner.getInstanceAdminClient();
Instance instance = insAdminClient
.createInstance(
InstanceInfo
.newBuilder(instanceId)
.setNodeCount(1)
.setDisplayName("Test instance")
.setInstanceConfigId(instanceConfig)
.build()
)
.get();
return instanceId;
}
private void createDatabase(Spanner spanner) throws InterruptedException, ExecutionException {
DatabaseAdminClient dbAdminClient = spanner.getDatabaseAdminClient();
Database database = dbAdminClient
.createDatabase(
INSTANCE_ID,
"order_schema",
Arrays.asList("CREATE TABLE Orders (orderId INT64 NOT NULL, name STRING(255), order_status STRING(255)) PRIMARY KEY (orderId)")
)
.get();
}
private Spanner spanner(){
SpannerOptions options = SpannerOptions
.newBuilder()
.setEmulatorHost(spannerEmulatorContainer.getEmulatorGrpcEndpoint())
.setCredentials(NoCredentials.getInstance())
.setProjectId(PROJECT_ID)
.build();
Spanner spanner = options.getService();
return spanner;
}
Now we are ready to run our integration test.
@Test
public void testOrders() throws ExecutionException, InterruptedException {
//Create Spanner Instance, DB, Table
Spanner spanner = spanner();
InstanceId instanceId = createInstance(spanner);
createDatabase(spanner);
//Create Order and Save
Order order = new Order();
order.setOrder_status("COMPLETED");
order.setName("Order1");
String message = this.orderService.save(order);
assertEquals("Order Saved Successfully", message);
//Validate
List<Order> orders = this.orderService.findOrdersByName("Order1");
assertTrue(orders.size() == 1);
assertTrue(orders.get(0).getOrder_status().equals("COMPLETED"));
}
Wrapping Up
Testcontainers helps in writing reliable integration tests. It is easy to implement; plus, the documentation is clear and crisp. Testcontainers GCloud simplifies the development of services using Google Cloud components as we can avoid connecting to the cloud and perform integration testing locally.
Opinions expressed by DZone contributors are their own.
Comments