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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Integrating Jenkins With Playwright TypeScript: A Complete Guide
  • Supercharging Pytest: Integration With External Tools
  • Mocking and Its Importance in Integration and E2E Testing
  • Seamless CI/CD Integration: Playwright and GitHub Actions

Trending

  • Rust, WASM, and Edge: Next-Level Performance
  • Enforcing Architecture With ArchUnit in Java
  • Monolith: The Good, The Bad and The Ugly
  • Event-Driven Microservices: How Kafka and RabbitMQ Power Scalable Systems
  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
7.9K 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

  • Integrating Jenkins With Playwright TypeScript: A Complete Guide
  • Supercharging Pytest: Integration With External Tools
  • Mocking and Its Importance in Integration and E2E Testing
  • Seamless CI/CD Integration: Playwright and GitHub Actions

Partner Resources

×

Comments
Oops! Something Went Wrong

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!