Partner – DBSchema – NPI EA (tag = Spring Data JPA)
announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema .

The way it does all of that is by using a design model , a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

Take a look at DBSchema

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

Azure Spring Apps is a fully managed service from Microsoft (built in collaboration with VMware), focused on building and deploying Spring Boot applications on Azure Cloud without worrying about Kubernetes.

The Enterprise plan comes with some interesting features, such as commercial Spring runtime support, a 99.95% SLA and some deep discounts (up to 47%) when you are ready for production.

>> Learn more and deploy your first Spring Boot app to Azure.

And, you can participate in a very quick (1 minute) paid user research from the Java on Azure product team.

Partner – Aegik AB – NPI EA (cat=JPA)
announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only , so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server's performance, with most of the profiling work done separately - so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server , hit the record button, and you'll have results within minutes:

out the Profiler

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

A quick guide to materially improve your tests with Junit 5:

>> The Junit 5 handbook
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 – RwS – NPI EA (cat=REST)
announcement - icon

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

REST With Spring (new)

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

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

>> LEARN SPRING

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

The AI Assistant to boost Boost your productivity writing unit tests - Machinet AI .

AI is all the rage these days, but for very good reason. The highly practical coding companion, you'll get the power of AI-assisted coding and automated unit test generation .
Machinet's Unit Test AI Agent utilizes your own project context to create meaningful unit tests that intelligently aligns with the behavior of the code.
And, the AI Chat crafts code and fixes errors with ease, like a helpful sidekick.

Simplify Your Coding Journey with Machinet AI :

>> Install Machinet AI in your IntelliJ

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

Get non-trivial analysis (and trivial, too!) suggested right inside your IDE or Git platform so you can code smart, create more value, and stay confident when you push.

Get CodiumAI for free and become part of a community of over 280,000 developers who are already experiencing improved and quicker coding.

Write code that works the way you meant it to:

CodiumAI. Meaningful Code Tests for Busy Devs

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

Looking for the ideal Linux distro for running modern Spring apps in the cloud?

Meet Alpaquita Linux : lightweight, secure, and powerful enough to handle heavy workloads.

This distro is specifically designed for running Java apps . It builds upon Alpine and features significant enhancements to excel in high-density container environments while meeting enterprise-grade security standards.

Specifically, the container image size is ~30% smaller than standard options, and it consumes up to 30% less RAM:

Alpaquita Containers now.

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

Partner – DBSchema – NPI EA (tag = SQL)
announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema .

The way it does all of that is by using a design model , a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

Take a look at DBSchema

Partner – Aegik AB – NPI EA (tag = SQL)
announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only , so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server's performance, with most of the profiling work done separately - so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server , hit the record button, and you'll have results within minutes:

out the Profiler

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

Course – LS – All
announcement - icon

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

>> CHECK OUT THE COURSE

1. Introduction

CompletableFuture is a powerful tool for asynchronous programming in Java. It provides a convenient way to chain asynchronous tasks together and handle their results . It is commonly used in situations where asynchronous operations need to be performed, and their results need to be consumed or processed at a later stage.

However, unit testing CompletableFuture can be challenging due to its asynchronous nature . Traditional testing methods, which rely on sequential execution, often fall short of capturing the nuances of asynchronous code. In this tutorial, we’ll discuss how to effectively unit test CompletableFuture using two different approaches: black-box testing and state-based testing.

2. Challenges of Testing Asynchronous Code

Asynchronous code introduces challenges due to its non-blocking and concurrent execution , posing difficulties in traditional testing methods. These challenges include:

  • Timing Issues: Asynchronous operations introduce timing dependencies into the code, making it difficult to control the execution flow and verify the behavior of the code at specific points in time. Traditional testing methods that rely on sequential execution may not be suitable for asynchronous code.
  • Exception Handling: Asynchronous operations can potentially throw exceptions, and it’s crucial to ensure that the code handles these exceptions gracefully and doesn’t fail silently. Unit tests should cover various scenarios to validate exception handling mechanisms.
  • Race Conditions: Asynchronous code can lead to race conditions, where multiple threads or processes attempt to access or modify shared data simultaneously, potentially resulting in unexpected outcomes.
  • Test Coverage: Achieving comprehensive test coverage for asynchronous code can be challenging due to the complexity of interactions and the potential for non-deterministic outcomes.
  • 3. Black-Box Testing

    Black-box testing focuses on testing the external behavior of the code without knowledge of its internal implementation . This approach is suitable for validating asynchronous code behavior from the user’s perspective. The tester only knows the inputs and expected outputs of the code.

    When testing CompletableFuture using black-box testing, we prioritize the following aspects:

  • Successful Completion: Verifying that the CompletableFuture completes successfully, returning the anticipated result.
  • Exception Handling: Validating that the CompletableFuture handles exceptions gracefully, preventing silent failures.
  • Timeouts: Ensuring that the CompletableFuture behaves as expected when encountering timeouts.
  • We can use a mocking framework like Mockito to mock the dependencies of the CompletableFuture under test. This will allow us to isolate the CompletableFuture and test its behavior in a controlled environment.

    3.1. System Under Test

    We will be testing a method named processAsync() that encapsulates the asynchronous data retrieval and combination process. This method accepts a list of Microservice objects as input and returns a CompletableFuture<String> . Each Microservice object represents a microservice capable of performing an asynchronous retrieval operation.

    The processAsync() utilizes two helper methods, fetchDataAsync() and combineResults() , to handle the asynchronous data retrieval and combination tasks:

    CompletableFuture<String> processAsync(List<Microservice> microservices) {
        List<CompletableFuture<String>> dataFetchFutures = fetchDataAsync(microservices);
        return combineResults(dataFetchFutures);
    

    The fetchDataAsync() method streams through the Microservice list, invoking retrieveAsync() for each, and returns a list of CompletableFuture<String>:

    private List<CompletableFuture<String>> fetchDataAsync(List<Microservice> microservices) {
        return microservices.stream()
            .map(client -> client.retrieveAsync(""))
            .collect(Collectors.toList());
    

    The combineResults() method uses CompletableFuture.allOf() to wait for all futures in the list to complete. Once complete, it maps the futures, joins the results, and returns a single string:

    private CompletableFuture<String> combineResults(List<CompletableFuture<String>> dataFetchFutures) {
        return CompletableFuture.allOf(dataFetchFutures.toArray(new CompletableFuture[0]))
          .thenApply(v -> dataFetchFutures.stream()
            .map(future -> future.exceptionally(ex -> {
                throw new CompletionException(ex);
              .join())
          .collect(Collectors.joining()));
    

    3.2. Test Case: Verify Successful Data Retrieval and Combination

    This test case verifies that the processAsync() method correctly retrieves data from multiple microservices and combines the results into a single string:

    @Test
    public void givenAsyncTask_whenProcessingAsyncSucceed_thenReturnSuccess() 
      throws ExecutionException, InterruptedException {
        Microservice mockMicroserviceA = mock(Microservice.class);
        Microservice mockMicroserviceB = mock(Microservice.class);
        when(mockMicroserviceA.retrieveAsync(any())).thenReturn(CompletableFuture.completedFuture("Hello"));
        when(mockMicroserviceB.retrieveAsync(any())).thenReturn(CompletableFuture.completedFuture("World"));
        CompletableFuture<String> resultFuture = processAsync(List.of(mockMicroserviceA, mockMicroserviceB));
        String result = resultFuture.get();
        assertEquals("HelloWorld", result);
    

    3.3. Test Case: Verify Exception Handling When Microservice Throws an Exception

    This test case verifies that the processAsync() method throws an ExecutionException when one of the microservices throws an exception. It also asserts that the exception message is the same as the exception thrown by the microservice:

    @Test
    public void givenAsyncTask_whenProcessingAsyncWithException_thenReturnException() 
      throws ExecutionException, InterruptedException {
        Microservice mockMicroserviceA = mock(Microservice.class);
        Microservice mockMicroserviceB = mock(Microservice.class);
        when(mockMicroserviceA.retrieveAsync(any())).thenReturn(CompletableFuture.completedFuture("Hello"));
        when(mockMicroserviceB.retrieveAsync(any()))
          .thenReturn(CompletableFuture.failedFuture(new RuntimeException("Simulated Exception")));
        CompletableFuture<String> resultFuture = processAsync(List.of(mockMicroserviceA, mockMicroserviceB));
        ExecutionException exception = assertThrows(ExecutionException.class, resultFuture::get);
        assertEquals("Simulated Exception", exception.getCause().getMessage());
    

    3.4. Test Case: Verify Timeout Handling When Combined Result Exceeds Timeout

    This test case attempts to retrieve the combined result from the processAsync() method within a specified timeout of 300 milliseconds. It asserts that a TimeoutException is thrown when the timeout is exceeded:

    @Test
    public void givenAsyncTask_whenProcessingAsyncWithTimeout_thenHandleTimeoutException() 
      throws ExecutionException, InterruptedException {
        Microservice mockMicroserviceA = mock(Microservice.class);
        Microservice mockMicroserviceB = mock(Microservice.class);
        Executor delayedExecutor = CompletableFuture.delayedExecutor(200, TimeUnit.MILLISECONDS);
        when(mockMicroserviceA.retrieveAsync(any()))
          .thenReturn(CompletableFuture.supplyAsync(() -> "Hello", delayedExecutor));
        Executor delayedExecutor2 = CompletableFuture.delayedExecutor(500, TimeUnit.MILLISECONDS);
        when(mockMicroserviceB.retrieveAsync(any()))
          .thenReturn(CompletableFuture.supplyAsync(() -> "World", delayedExecutor2));
        CompletableFuture<String> resultFuture = processAsync(List.of(mockMicroserviceA, mockMicroserviceB));
        assertThrows(TimeoutException.class, () -> resultFuture.get(300, TimeUnit.MILLISECONDS));
    

    The above code uses CompletableFuture.delayedExecutor() to create executors that will delay the completion of the retrieveAsync() calls by 200 and 500 milliseconds, respectively. This simulates the delays caused by the microservices and allows the test to verify that the processAsync() method handles timeouts correctly.

    4. State-Based Testing

    State-based testing focuses on verifying the state transitions of the code as it executes. This approach is particularly useful for testing asynchronous code, as it allows testers to track the code’s progress through different states and ensure that it transitions correctly.

    For example, we can verify that the CompletableFuture transitions to the completed state when the asynchronous task is completed successfully. Otherwise, it transits to a failed state when an exception occurs, or the task is cancelled due to interruption.

    4.1. Test Case: Verify State After Successful Completion

    This test case verifies that a CompletableFuture instance transitions to the done state when all of its constituent CompletableFuture instances have been completed successfully:

    @Test
    public void givenCompletableFuture_whenCompleted_thenStateIsDone() {
        Executor delayedExecutor = CompletableFuture.delayedExecutor(200, TimeUnit.MILLISECONDS);
        CompletableFuture<String> cf1 = CompletableFuture.supplyAsync(() -> "Hello", delayedExecutor);
        CompletableFuture<String> cf2 = CompletableFuture.supplyAsync(() -> " World");
        CompletableFuture<String> cf3 = CompletableFuture.supplyAsync(() -> "!");
        CompletableFuture<String>[] cfs = new CompletableFuture[] { cf1, cf2, cf3 };
        CompletableFuture<Void> allCf = CompletableFuture.allOf(cfs);
        assertFalse(allCf.isDone());
        allCf.join();
        String result = Arrays.stream(cfs)
          .map(CompletableFuture::join)
          .collect(Collectors.joining());
        assertFalse(allCf.isCancelled());
        assertTrue(allCf.isDone());
        assertFalse(allCf.isCompletedExceptionally());
    

    4.2. Test Case: Verify State After Completing Exceptionally

    This test case verifies that when one of the constituent CompletableFuture instances cf2 completes exceptionally, and the allCf CompletableFuture transitions to the exceptional state:

    @Test
    public void givenCompletableFuture_whenCompletedWithException_thenStateIsCompletedExceptionally() 
      throws ExecutionException, InterruptedException {
        Executor delayedExecutor = CompletableFuture.delayedExecutor(200, TimeUnit.MILLISECONDS);
        CompletableFuture<String> cf1 = CompletableFuture.supplyAsync(() -> "Hello", delayedExecutor);
        CompletableFuture<String> cf2 = CompletableFuture.failedFuture(new RuntimeException("Simulated Exception"));
        CompletableFuture<String> cf3 = CompletableFuture.supplyAsync(() -> "!");
        CompletableFuture<String>[] cfs = new CompletableFuture[] { cf1, cf2, cf3 };
        CompletableFuture<Void> allCf = CompletableFuture.allOf(cfs);
        assertFalse(allCf.isDone());
        assertFalse(allCf.isCompletedExceptionally());
        assertThrows(CompletionException.class, allCf::join);
        assertTrue(allCf.isCompletedExceptionally());
        assertTrue(allCf.isDone());
        assertFalse(allCf.isCancelled());
    

    4.3. Test Case: Verify State After Task Cancelled

    This test case verifies that when the allCf CompletableFuture is canceled using the cancel(true) method, it transitions to the cancelled state:

    @Test
    public void givenCompletableFuture_whenCancelled_thenStateIsCancelled() 
      throws ExecutionException, InterruptedException {
        Executor delayedExecutor = CompletableFuture.delayedExecutor(200, TimeUnit.MILLISECONDS);
        CompletableFuture<String> cf1 = CompletableFuture.supplyAsync(() -> "Hello", delayedExecutor);
        CompletableFuture<String> cf2 = CompletableFuture.supplyAsync(() -> " World");
        CompletableFuture<String> cf3 = CompletableFuture.supplyAsync(() -> "!");
        CompletableFuture<String>[] cfs = new CompletableFuture[] { cf1, cf2, cf3 };
        CompletableFuture<Void> allCf = CompletableFuture.allOf(cfs);
        assertFalse(allCf.isDone());
        assertFalse(allCf.isCompletedExceptionally());
        allCf.cancel(true);
        assertTrue(allCf.isCancelled());
        assertTrue(allCf.isDone());
    

    5. Conclusion

    In conclusion, unit testing CompletableFuture can be challenging due to its asynchronous nature. However, it is an important part of writing robust and maintainable asynchronous code. By using black-box and state-based testing approaches, we can assess the behavior of our CompletableFuture code under various conditions, ensuring that it functions as expected and handles potential exceptions gracefully.

    As always, the example code is available over on GitHub.

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

    Just published a new writeup on how to run a standard Java/Boot application as a Docker container, using the Liberica JDK on top of Alpaquita Linux:

    Spring Boot Application on Liberica Runtime Container.

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

    Looking for the ideal Linux distro for running modern Spring apps in the cloud?

    Meet Alpaquita Linux: lightweight, secure, and powerful enough to handle heavy workloads.

    This distro is specifically designed for running Java apps. It builds upon Alpine and features significant enhancements to excel in high-density container environments while meeting enterprise-grade security standards.

    Specifically, the container image size is ~30% smaller than standard options, and it consumes up to 30% less RAM:

    Alpaquita Containers now.

    Partner – Aegik AB – NPI EA (tag = SQL)
    announcement - icon

    Slow MySQL query performance is all too common. Of course it is.

    The Jet Profiler was built entirely for MySQL, so it's fine-tuned for it and does advanced everything with relaly minimal impact and no server changes.

    out the Profiler

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

    Explore the secure, reliable, and high-performance Test Execution Cloud built for scale. Right in your IDE:

    CodiumAI. Meaningful Code Tests for Busy Devs

    Basically, write code that works the way you meant it to.

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

    AI is all the rage these days, but for very good reason. The highly practical coding companion, you'll get the power of AI-assisted coding and automated unit test generation.
    Machinet's Unit Test AI Agent utilizes your own project context to create meaningful unit tests that intelligently aligns with the behavior of the code.

    Simplify Your Coding Journey with Machinet AI:

    >> Install Machinet AI in your IntelliJ

    Course – LS – All
    announcement - icon

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

    >> CHECK OUT THE COURSE

    res – REST with Spring (eBook) (everywhere)
    Download the Guide
    eBook – Video Security – NPI EA (cat=Spring Security)
    access to the video
    eBook – Persistence – NPI EA (cat=Persistence)