Baeldung

Java, Spring and Web Development tutorials

 

Implement Unit Test in gRPC Service
2025-09-15 03:45 UTC by Saikat Chakraborty

start here featured

1. Overview

gRPC is a high-performance, open-source RPC framework which is supported by the HTTP/2 protocol, enabling more straightforward implementation of the API schema definition and automatically generating boilerplate stub code.

Unit testing the gRPC service can be slightly complex due to its underlying constructs, such as the server, channel, and serialization.

In this tutorial, we’ll learn how to implement a gRPC service in Java. We’ll also write the unit tests using the support provided by the gRPC framework.

2. Implement the gRPC Service

Let’s imagine we need to build a gRPC service that returns some data to the client.

2.1. Maven Dependencies

We’ll include the grpc-netty-shaded, grpc-protobuf and grpc-stub dependencies related to gRPC:

<dependency>
    <groupId>io.grpc</groupId>
    <artifactId>grpc-netty-shaded</artifactId>
    <scope>runtime</scope>
    <version>1.75.0</version>
</dependency>
<dependency>
    <groupId>io.grpc</groupId>
    <artifactId>grpc-protobuf</artifactId>
    <version>1.75.0</version>
</dependency>
<dependency>
    <groupId>io.grpc</groupId>
    <artifactId>grpc-stub</artifactId>
    <version>1.63.0</version>
</dependency>

Next, we’ll define the API contract.

2.2. Define the Service Using Proto File

The RPC service, request and response schema will be defined using the protocol buffer file.

First, we’ll define the UserService contract in the user_service.proto file:

syntax = "proto3";
package userservice;
option java_multiple_files = true;
option java_package = "com.baeldung.grpc.userservice";
service UserService {
  rpc GetUser(UserRequest) returns (UserResponse);
}

In the above code, we defined the RPC GetUser service with the UserRequest as input and the UserResponse as output.

Then, we’ll define the UserRequest, UserResponse and the User message schema in the same file:

message UserRequest {
  int32 id = 1;
}
message UserResponse {
  User user = 1;
}
message User {
  int32 id = 1;
  string name = 2;
  string email = 3;
}

We should note that the property’s value is the tag or sequence number that gRPC uses for serialization.

2.3. Generate the Stub Class

We’ll automatically generate the gRPC stub and request/response classes from the user_service.proto file.

We’ll add the protobuf-maven-plugin to the existing pom.xml file:

<plugin>
    <groupId>org.xolstice.maven.plugins</groupId>
    <artifactId>protobuf-maven-plugin</artifactId>
    <version>0.6.1</version>
    <configuration>
        <protocArtifact>com.google.protobuf:protoc:3.3.0:exe:${os.detected.classifier}</protocArtifact>
        <pluginId>grpc-java</pluginId>
        <pluginArtifact>io.grpc:protoc-gen-grpc-java:1.4.0:exe:${os.detected.classifier}</pluginArtifact>
    </configuration>
    <executions>
        <execution>
            <goals>
                <goal>compile</goal>
                <goal>compile-custom</goal>
            </goals>
        </execution>
    </executions>
</plugin>

The protobuf-maven-plugin plugin will generate the required classes in the project’s target folder.

2.4. Implement the Service

We’ll need to implement the getUser method in the base UserServiceImplBase class. This method will return the user fetched from a repository.

Additionally, as in any production environment, it’s expected to have edge cases, for example, a user not found. We can handle this scenario by throwing a custom RuntimeException along with the relevant gRPC NOT_FOUND status code and a description. gRPC has a set of status codes with similar meaning to that of HTTP status codes.

Let’s override the getUser method defined in the UserServiceImplBase class:

@Override
public void getUser(UserRequest request, StreamObserver<UserResponse> responseObserver) {
    try {
        User user = Optional.ofNullable(userRepositoryMap.get(request.getId()))
          .orElseThrow(() -> new UserNotFoundException(request.getId()));
        UserResponse response = UserResponse.newBuilder()
          .setUser(user)
          .build();
        responseObserver.onNext(response);
        responseObserver.onCompleted();
        logger.info("Return User for id {}", request.getId());
    } catch (UserNotFoundException ex) {
        responseObserver.onError(Status.NOT_FOUND.withDescription(ex.getMessage()).asRuntimeException());
    }
}

In the above code, we retrieve the user from a map repository and set it in the StreamObserver object.

Also, we’ll implement the custom UserNotFoundException class:

public class UserNotFoundException extends RuntimeException {
    public UserNotFoundException(int userId) {
        super(String.format("User not found with ID %s", userId));
    }
}

Next, we’ll test the above gRPC service.

3. Testing the gRPC Service

We need to test the getUser service within the gRPC server context, thereby testing the serialization/deserialization, interceptors and message propagation.

3.1. Maven Dependency

For the ease of testing, gRPC provides both the in-process/in-memory Server and Channel implementations in a testing library.

We’ll add the grpc-testing test dependency in the pom.xml file:

<dependency>
    <groupId>io.grpc</groupId>
    <artifactId>grpc-testing</artifactId>
    <version>1.75.0</version>
    <scope>test</scope>
</dependency>

Next, we’ll set up the test class using the support provided in the library.

3.2. Setup of Unit Tests

The grpc-testing library provides the InProcessServerBuilder and InProcessChannelBuilder classes to support testing.

First, let’s write a test class with the Server and a ManagedChannel instance along with the UserServiceBlockingStub class:

public class UserServiceUnitTest {
    private UserServiceGrpc.UserServiceBlockingStub userServiceBlockingStub;
    private Server inProcessServer;
    private ManagedChannel managedChannel;
    @BeforeEach
    void setup() throws IOException {
        String serviceName = InProcessServerBuilder.generateName();
        inProcessServer = InProcessServerBuilder.forName(serviceName)
          .directExecutor()
          .addService(new UserServiceImpl())
          .build()
          .start();
       
        managedChannel = InProcessChannelBuilder.forName(serviceName)
          .directExecutor()
          .usePlaintext()
          .build();
        userServiceBlockingStub = UserServiceGrpc.newBlockingStub(managedChannel);
    }
}

In the above code, we added the actual service UserServiceImpl object to the Server instance and then assigned the ManagedChannel object to the UserServiceBlockingStub class.

We should note that the server runs in the same test process and does not involve any socket or TCP overhead. This way, the test runs fast, reliable and independent of the network stack.

3.3. Implementation of the Unit Tests

We’ll implement a test scenario where the user exists in the service.

Let’s call the getUser method with a valid id and verify the response:

@Test
void givenUserIsPresent_whenGetUserIsCalled_ThenReturnUser() {
    UserRequest userRequest = UserRequest.newBuilder()
      .setId(1)
      .build();
    UserResponse userResponse = userServiceBlockingStub.getUser(userRequest);
    assertNotNull(userResponse);
    assertNotNull(userResponse.getUser());
    assertEquals(1, userResponse.getUser().getId());
    assertEquals("user1", userResponse.getUser().getName());
    assertEquals("user1@example.com", userResponse.getUser().getEmail());
}

We can test the user does not exist scenario:

@Test
void givenUserIsNotPresent_whenGetUserIsCalled_ThenThrowRuntimeException(){
    UserRequest userRequest = UserRequest.newBuilder()
      .setId(1000)
      .build();
    StatusRuntimeException statusRuntimeException = assertThrows(StatusRuntimeException.class,
      () -> userServiceBlockingStub.getUser(userRequest));
    assertNotNull(statusRuntimeException);
    assertNotNull(statusRuntimeException.getStatus());
    assertEquals(Status.NOT_FOUND.getCode(), statusRuntimeException.getStatus().getCode());
    assertTrue(statusRuntimeException.getStatus().getDescription().contains("User not found with ID 1000"));
}

In the above assertions, we’ve verified that the exception contains the NOT_FOUND status code and description as defined earlier.

We should note that the gRPC implementation converts the custom UserNotFoundException into a StatusRuntimeException to the client.

4. Implement the gRPC Client

The generated stub UserServiceBlockingStub class from the user_service.proto file will be used by the client-side code.

First, we’ll construct the UserServiceBlockingStub and ManagedChannel in the UserClient class:

public class UserClient {
    private final UserServiceGrpc.UserServiceBlockingStub userServiceStub;
    private final ManagedChannel managedChannel;
    public UserClient(ManagedChannel managedChannel, UserServiceGrpc.UserServiceBlockingStub userServiceStub) {
        this.managedChannel = managedChannel;
        this.userServiceStub = UserServiceGrpc.newBlockingStub(managedChannel);
    }
}

Then, let’s add the getUser method in the UserClient class:

public User getUser(int id) {
    UserRequest userRequest = UserRequest.newBuilder()
      .setId(id)
      .build();
    return userServiceStub.getUser(userRequest).getUser();
}

In the above code, we’re calling the stub’s getUser method as if calling a local method, though in reality it’s a remote procedure call.

5. Testing the Client

We can now test the UserClient class as done earlier in the server-side code. However, we need to provide a mocked or fake UserServiceImplBase service.

First, we’ll write the test setup method with the Server, ManagedChannel, mocked UserServiceImplBase and UserClient:

@BeforeEach
public void setup() throws Exception {
    String serverName = InProcessServerBuilder.generateName();
    mockUserService = spy(UserServiceGrpc.UserServiceImplBase.class);
    inProcessServer = InProcessServerBuilder
      .forName(serverName)
      .directExecutor()
      .addService(mockUserService.bindService())
      .build()
      .start();
        
    managedChannel = InProcessChannelBuilder.forName(serverName)
      .directExecutor()
      .usePlainText()
      .build();
        
    userClient = new UserClient(managedChannel);
}

Then, let’s add a helper method to mock the GetUser method using Mockito:

private void mockGetUser(User expectedUser) {
    Mockito.doAnswer(invocation -> {
        StreamObserver<UserResponse> observer = invocation.getArgument(1);
        UserResponse response = UserResponse.newBuilder()
          .setUser(expectedUser)
          .build();
        observer.onNext(response);
        observer.onCompleted();
        return null;
    }).when(mockUserService).getUser(any(), any());
}

Finally, we’ll implement the test case where the user exists:

@Test
void givenUserIsPresent_whenGetUserIsCalled_ThenReturnUser() {
    User expectedUser = User.newBuilder()
      .setId(1)
      .setName("user1")
      .setEmail("user1@example.com")
      .build();
    mockGetUser(expectedUser);
    User user = userClient.getUser(1);
    assertEquals(expectedUser, user);
}

We’ll run the above test case and confirm that the assertion passes.

6. Conclusion

In this tutorial, we’ve learned how to implement a gRPC service in Java using the .proto file. We’ve also implemented unit tests using the in-memory Server and ManagedChannel instance provided by the gRPC framework in both the server-side and client-side.

As always, the example code can be found over on GitHub.

The post Implement Unit Test in gRPC Service first appeared on Baeldung.
       

 

Content mobilized by FeedBlitz RSS Services, the premium FeedBurner alternative.