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
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Share Delta Lake Tables Between Databricks and Snowflake
  • Designing Memory Architecture for Stateful AI Agents: Short-Term Context and Long-Term Persistence
  • Moving 900+ GB of Prometheus Without a Cutover Weekend
  • How Go Maps Work: From Buckets to Swiss Tables

Trending

  • Why AI Agents Need a Shared Enterprise Ontology
  • Build a Voice Assistant With Gemini Live API
  • Stop Writing Database Migration Scripts: Declarative Schema Sync for Java
  • Should Developers Switch From SQLite to DuckDB?

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  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
DZone Core CORE ·
Oct. 23, 22 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
8.1K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Share Delta Lake Tables Between Databricks and Snowflake
  • Designing Memory Architecture for Stateful AI Agents: Short-Term Context and Long-Term Persistence
  • Moving 900+ GB of Prometheus Without a Cutover Weekend
  • How Go Maps Work: From Buckets to Swiss Tables

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • 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