Search code examples
javaspring-bootunit-testingjunitmockito

Java unit test - exception not being thrown


Trying to write a test that will call my method, when that method makes a call to another method we will throw a custom exception i have made. Here i have simplified it all

2 functions

public MyJsonResponse hello() {
        MyJsonResponse response = new MyJsonResponse();
        response.setErrorMessage("1");
        response.setStatus("some status");
        response.setData("1");
        response.setHttpResponse(200);
        try{
            hi();
            return response;
        }catch (MyServiceException e) {
            response.setErrorMessage(e.getMessage());
            response.setStatus("error creating");
            response.setData("2");
            response.setHttpResponse(e.getResponseStatus());
            return response;
        }

    }

    public String hi() throws  MyServiceException{
        LOG.error("Exception");
        return "yea";
    }

The test I have written is this

    @Test
    public void myTest() throws Exception {

        given(service.hi()).willAnswer( invocation -> { throw new MyServiceException("abc msg",511); });
        MyJsonResponse actual = service.hello();

        Assert.assertNotNull(actual);
        assertEquals(511, actual.getHttpResponse());
    }

But unfortunately the result is as follows

java.lang.AssertionError: 
Expected :511
Actual   :200

Solution

  • Please, be sure that you are using a spy as you want to use the actual code for some methods of your mocked service and just stubbing specific methods of it. Please, see for instance this related SO question about the subject.

    Also, consider modifying your test definition to use willThrow instead of willAnswer: as pointed out by @eis, you can still use the later, but the former is more straightforward.

    Your code will look similar to this:

    @Test
    public void myTest() throws Exception {
      MyService service = spy(MyService.class);
    
      willThrow(new MyServiceException("abc msg",511))
        .given(service)
        .hi()
      ;
    
      // As pointed out by @eis, you can still use willAnswer
      // willAnswer(
      //   invocation -> { throw new MyServiceException("abc msg",511);}
      // )
      //   .given(service)
      //   .hi()
      // ;
    
      
      MyJsonResponse actual = service.hello();
    
      Assert.assertNotNull(actual);
      assertEquals(511, actual.getHttpResponse());
    }