title: How can I use Mockito.doThrow in a micronaut test to simulate exceptions thrown by a service call?
body: <p>I want to simulate a few possible exceptions thrown during a service method call. I wrote the following micronaut test (I am using micronaut 1.1.2 
  ):</p>
  
  <pre><code>@MicronautTest
  public class HelloWorldControllerTest {
  
     @Inject
     private AcmeService acmeService;
     @Inject
     @Client("/")
     private RxHttpClient client;
  
     @MockBean(AcmeService.class)
     public AcmeService acmeService() {
        return Mockito.mock(AcmeService.class);
     }
  
     @Test
     public void test_without_exception() {
  
        HttpResponse httpResponse = client.toBlocking().exchange(HttpRequest.GET("/"));
        Assertions.assertEquals(HttpStatus.OK, httpResponse.getStatus());
     }
  
     @Test
     public void test_with_nullpointer_exception() {
  
        Mockito.doThrow(new NullPointerException("nullpointer"))
              .when(acmeService)
              .doSomething(Mockito.anyString());
  
        HttpClientResponseException responseException = Assertions.assertThrows(HttpClientResponseException.class,
              () -&gt; client.toBlocking().exchange(HttpRequest.GET("/")));
  
        Assertions.assertEquals("Internal Server Error: nullpointer", responseException.getMessage());
     }
  
     @Test
     public void test_with_illegal_argument_exception() {
  
         Mockito.doThrow(new IllegalArgumentException("illegal"))
              .when(acmeService)
              .doSomething(Mockito.anyString());
  
         HttpClientResponseException responseException = Assertions.assertThrows(HttpClientResponseException.class,
              () -&gt; client.toBlocking().exchange(HttpRequest.GET("/")));
  
         Assertions.assertEquals("Internal Server Error: illegal", responseException.getMessage());
     }
  }
  </code></pre>
  
  <p>The problem is when the whole test class is executed, only the first test pass, the second and the third fail because no exception is thrown (I am expecting exceptions thrown). But if I execute each test separately, every test pass (exception thrown as expected).</p>
  
  <p>Mocking of AcmeService isn't working correctly. I also tried to reset the mock (Mockito.reset) after each test, but this isn't working either.</p>
  
  <p>I am not able to simulate exceptions thrown during service execution. Debugging shows, that in every test case the mocked service is different. The mocked service used by the hello world controller is also different (that's why it isn't working).</p>
  
  <p>The mocking examples of <a href="https://micronaut-projects.github.io/micronaut-test/latest/guide/index.html" rel="nofollow noreferrer">https://micronaut-projects.github.io/micronaut-test/latest/guide/index.html</a> show no difference.</p>
  
  <p>So, my question is, how can I simulate different exceptions thrown by the service. Why isn't my test working?</p>
  
  <p>I appreciate your thoughts.</p>