Simulate completion of an exception in a test

I have a class HttpClientthat has a function that returns CompletableFuture:

public class HttpClient {

  public static CompletableFuture<int> getSize() {
      CompletableFuture<int> future = ClientHelper.getResults()
                 .thenApply((searchResults) -> {
                    return searchResults.size();
                });

      return future;
   }
}

Then another function calls this function:

public class Caller {

   public static void caller() throws Exception {
       // some other code than can throw an exception
       HttpClient.getSize()
       .thenApply((count) -> {
          System.out.println(count);
          return count;
       })
       .exceptionally(ex -> {
          System.out.println("Whoops! Something happened....");
       });
   }
}

Now I want to write a test to simulate what ClientHelper.getResults does not work , so for this I wrote this:

@Test
public void myTest() {
    HttpClient mockClient = mock(HttpClient.class);

    try {
        Mockito.doThrow(new CompletionException(new Exception("HTTP call failed")))
                .when(mockClient)
                .getSize();

        Caller.caller();

    } catch (Exception e) {
        Assert.fail("Caller should not have thrown an exception!");
    }
}

This test fails. The code inside exceptionallywill never be executed. However, if I usually run the source code and the HTTP call fails, it fits the block perfectly exceptionally.

How do I write a test so that the code runs exceptionally?

+4
source share
1 answer

, :

CompletableFuture<Long> future = new CompletableFuture<>();
future.completeExceptionally(new Exception("HTTP call failed!"));

Mockito.when(mockClient.getSize())
        .thenReturn(future);

, .

+6

Source: https://habr.com/ru/post/1683601/


All Articles