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 Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
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
Partner Zones AWS Cloud
by AWS Developer Relations
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
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  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.

Emmanouil Gkatziouras user avatar by
Emmanouil Gkatziouras
CORE ·
Oct. 23, 22 · Tutorial
Like (7)
Save
Tweet
Share
5.72K 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.

Popular on DZone

  • OpenVPN With Radius and Multi-Factor Authentication
  • How Agile Architecture Spikes Are Used in Shift-Left BDD
  • What To Know Before Implementing IIoT
  • How To Build a Spring Boot GraalVM Image

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: