DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • CI/CD Integration: Running Playwright on GitHub Actions: The Definitive Automation Blueprint
  • When Memory Overflows: Too Many ApplicationContexts in Spring Integration Tests
  • Integrating Selenium With Amazon S3 for Test Artifact Management
  • Integrating Jenkins With Playwright TypeScript: A Complete Guide

Trending

  • RAG Is Not Enough: Advanced Retrieval Architectures Using Vertex AI Search on GCP
  • Feature Flag Debt: Performance Impact in Enterprise Applications
  • Ujorm3: A New Lightweight ORM for JavaBeans and Records
  • Ingesting Fixed-Width Mainframe Files Into Delta Lake: The Details Nobody Writes Down
  1. DZone
  2. Data Engineering
  3. Databases
  4. Implement Testcontainers GCloud Module With Spring Boot for Writing Integration Tests

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.

By 
Sameer Shukla user avatar
Sameer Shukla
DZone Core CORE ·
Aug. 31, 22 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
8.4K Views

Join the DZone community and get the full member experience.

Join For Free

Testcontainers 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. 

Java
 
@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. 

Java
 
@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. 

Java
 
@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.

Java
 
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.

Spanner (database) Testing Integration

Opinions expressed by DZone contributors are their own.

Related

  • CI/CD Integration: Running Playwright on GitHub Actions: The Definitive Automation Blueprint
  • When Memory Overflows: Too Many ApplicationContexts in Spring Integration Tests
  • Integrating Selenium With Amazon S3 for Test Artifact Management
  • Integrating Jenkins With Playwright TypeScript: A Complete Guide

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook