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

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Recurrent Workflows With Cloud Native Dapr Jobs
  • Thermometer Continuation in Scala
  • Thumbnail Generator Microservice for PDF in Spring Boot
  • Docs That Write Themselves: Scaling With gRPC and Protobuf

Trending

  • Google Cloud Document AI Basics
  • Top Book Picks for Site Reliability Engineers
  • Integrating Security as Code: A Necessity for DevSecOps
  • Medallion Architecture: Why You Need It and How To Implement It With ClickHouse
  1. DZone
  2. Data Engineering
  3. Data
  4. Mock gRPC Services for Unit Testing

Mock gRPC Services for Unit Testing

Have gRPC services? Here's how to mock them easily for your testing.

By 
Emmanouil Gkatziouras user avatar
Emmanouil Gkatziouras
DZone Core CORE ·
Oct. 23, 22 · Tutorial
Likes (7)
Comment
Save
Tweet
Share
7.5K Views

Join the DZone community and get the full member experience.

Join For Free

In our day-to-day work, we develop applications that include interactions with software components through I/O. They can be a database, a broker, or some form of blob storage. Take, for example, the cloud components you interact with: Azure Storage Queue, SQS, Pub/Sub. The communication with those components usually happens with an SDK.

From the start, testing will kick in. Therefore, the interaction with those components should be tackled in a testing context. An approach is to use installations (or simulators) of those components and have the code interacting with an actual instance, just like the way it can be achieved by using test containers or by creating infrastructure for testing purposes only.
Another approach is to spin up a mock service of the components and have the tests interacting with it. A good example of this can be Hoverfly. A simulated HTTP service is run during testing and test cases interact with it. 

Both can be used on various situations depending on the qualities our testing process requires. We shall focus on the second approach applied on gRPC.

It is well known that most Google Cloud Components come with a gRPC API. In our scenario, we have an application publishing messages to Pub/Sub.

Let’s put the needed dependencies first:

XML
 
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>com.google.cloud</groupId>
            <artifactId>libraries-bom</artifactId>
            <version>24.1.2</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>
 
<dependencies>
    <dependency>
        <groupId>com.google.cloud</groupId>
        <artifactId>google-cloud-pubsub</artifactId>
    </dependency>
    <dependency>
        <groupId>io.grpc</groupId>
        <artifactId>grpc-testing</artifactId>
        <version>1.43.2</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>com.google.api.grpc</groupId>
        <artifactId>grpc-google-cloud-pubsub-v1</artifactId>
        <version>1.97.1</version>
        <scope>test</scope>
    </dependency>
</dependencies>

Let’s start with our publisher class.

Java
 
package com.egkatzioura.notification.publisher;
 
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
 
import com.google.api.core.ApiFuture;
import com.google.api.core.ApiFutureCallback;
import com.google.api.core.ApiFutures;
import com.google.cloud.pubsub.v1.Publisher;
import com.google.protobuf.ByteString;
import com.google.pubsub.v1.PubsubMessage;
 
public class UpdatePublisher {
 
    private final Publisher publisher;
    private final Executor executor;
 
    public UpdatePublisher(Publisher publisher, Executor executor) {
        this.publisher = publisher;
        this.executor = executor;
    }
 
    public CompletableFuture<String> update(String notification) {
        PubsubMessage pubsubMessage = PubsubMessage.newBuilder()
                                                           .setData(ByteString.copyFromUtf8(notification))
                                                                   .build();
        ApiFuture<String> apiFuture = publisher.publish(pubsubMessage);
 
        return toCompletableFuture(apiFuture);
    }
 
    private CompletableFuture<String> toCompletableFuture(ApiFuture<String> apiFuture) {
        final CompletableFuture<String> responseFuture = new CompletableFuture<>();
 
        ApiFutures.addCallback(apiFuture, new ApiFutureCallback<>() {
            @Override
            public void onFailure(Throwable t) {
                responseFuture.completeExceptionally(t);
            }
 
            @Override
            public void onSuccess(String result) {
                responseFuture.complete(result);
            }
 
        }, executor);
        return responseFuture;
    }
 
}

The publisher will send messages and return the CompletableFuture of the message ID sent.
So let’s test this class. Our goal is to sent a message and get the message id back. The service to mock and simulate is Pub/Sub.

For this purpose, we added the gRPC API dependency on Maven.

XML
 
<dependency>
    <groupId>com.google.api.grpc</groupId>
    <artifactId>grpc-google-cloud-pubsub-v1</artifactId>
    <version>1.97.1</version>
    <scope>test</scope>
</dependency>

We shall mock the API for publishing actions. The class to implement is PublisherGrpc.PublisherImplBase.

Java
 
package com.egkatzioura.notification.publisher;
 
import java.util.UUID;
 
import com.google.pubsub.v1.PublishRequest;
import com.google.pubsub.v1.PublishResponse;
import com.google.pubsub.v1.PublisherGrpc;
 
import io.grpc.stub.StreamObserver;
 
public class MockPublisherGrpc extends PublisherGrpc.PublisherImplBase {
 
    private final String prefix;
 
    public MockPublisherGrpc(String prefix) {
        this.prefix = prefix;
    }
 
    @Override
    public void publish(PublishRequest request, StreamObserver<PublishResponse> responseObserver) {
        responseObserver.onNext(PublishResponse.newBuilder().addMessageIds(prefix+":"+UUID.randomUUID().toString()).build());
        responseObserver.onCompleted();
    }
 
}

As you see, the message ID will have a prefix we define.

This would be the PublisherGrpc implementation on the server side. Let us proceed to our unit test. The UpdatePublisher class can have a Publisher injected. This publisher will be configured to use the PublisherGrpc.PublisherImplBase created previously.

Java
 
@Rule
public final GrpcCleanupRule grpcCleanup = new GrpcCleanupRule();
 
private static final String MESSAGE_ID_PREFIX = "message";
 
@Before
public void setUp() throws Exception {
String serverName = InProcessServerBuilder.generateName();
 
Server server = InProcessServerBuilder
.forName(serverName).directExecutor().addService(new MockPublisherGrpc(MESSAGE_ID_PREFIX)).build().start();
 
grpcCleanup.register(server);
...

Above we created a GRPC server that services in-process requests. Then we registered the mock service created previously.

Onward! We create the Publisher using that service and create an instance of the class to test.

Java
 
...
 
private UpdatePublisher updatePublisher;
 
@Before
public void setUp() throws Exception {
String serverName = InProcessServerBuilder.generateName();
 
Server server = InProcessServerBuilder
.forName(serverName).directExecutor().addService(new MockPublisherGrpc(MESSAGE_ID_PREFIX)).build().start();
 
grpcCleanup.register(server);
 
ExecutorProvider executorProvider = testExecutorProvider();
ManagedChannel managedChannel = InProcessChannelBuilder.forName(serverName).directExecutor().build();
 
TransportChannel transportChannel = GrpcTransportChannel.create(managedChannel);
TransportChannelProvider transportChannelProvider = FixedTransportChannelProvider.create(transportChannel);
 
String topicName = "projects/test-project/topic/my-topic";
Publisher publisher = Publisher.newBuilder(topicName)
.setExecutorProvider(executorProvider)
.setChannelProvider(transportChannelProvider)
.build();
 
updatePublisher = new UpdatePublisher(publisher, Executors.newSingleThreadExecutor());
...

We pass a Channel to our publisher which points to our InProcessServer. Requests will be routed to the service we registered. Finally, we can add our test.

Java
 
@Test
public void testPublishOrder() throws ExecutionException, InterruptedException {
String messageId = updatePublisher.update("Some notification").get();
assertThat(messageId, containsString(MESSAGE_ID_PREFIX));
}

We did it! We created our in-process gRPC server in order to have tests for our gRPC-driven services.

You can find the code on GitHub!

gRPC Data Types

Published at DZone with permission of Emmanouil Gkatziouras, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Recurrent Workflows With Cloud Native Dapr Jobs
  • Thermometer Continuation in Scala
  • Thumbnail Generator Microservice for PDF in Spring Boot
  • Docs That Write Themselves: Scaling With gRPC and Protobuf

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!