eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Partner – LambdaTest – NPI EA (cat=Testing)
announcement - icon

Regression testing is an important step in the release process, to ensure that new code doesn't break the existing functionality. As the codebase evolves, we want to run these tests frequently to help catch any issues early on.

The best way to ensure these tests run frequently on an automated basis is, of course, to include them in the CI/CD pipeline. This way, the regression tests will execute automatically whenever we commit code to the repository.

In this tutorial, we'll see how to create regression tests using Selenium, and then include them in our pipeline using GitHub Actions:, to be run on the LambdaTest cloud grid:

>> How to Run Selenium Regression Tests With GitHub Actions

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Partner – LambdaTest – NPI (cat= Testing)
announcement - icon

Regression testing is an important step in the release process, to ensure that new code doesn't break the existing functionality. As the codebase evolves, we want to run these tests frequently to help catch any issues early on.

The best way to ensure these tests run frequently on an automated basis is, of course, to include them in the CI/CD pipeline. This way, the regression tests will execute automatically whenever we commit code to the repository.

In this tutorial, we'll see how to create regression tests using Selenium, and then include them in our pipeline using GitHub Actions:, to be run on the LambdaTest cloud grid:

>> How to Run Selenium Regression Tests With GitHub Actions

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("[email protected]", 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("[email protected]")
      .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.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)