Mockito模拟void方法并抛出异常而不执行方法代码

时间:2018-10-19 17:02:09

标签: java junit mockito

我想模拟一个可以返回不同种类异常的void方法。我不想执行实际的方法。我只想在myResponse中查看正确的代码。

public Response myMethod(String a, String b){   
    MyResponse myresponse;
    try{
        classIWantToMock.save(a,b);
         myResponse = new MyResponse("200", SUCCESSFUL_OPERATION);
         return Response.ok(myResponse, MediaType.APPLICATION_JSON).build();
    }
    catch(NotFoundException ex){
         myResponse = new MyResponse("404", ex.getMessage());
         return Response.status(Status.NOT_FOUND).entity(myResponse).type(MediaType.APPLICATION_JSON).build();
    }
    catch(BadRequestException ex){
        myResponse = new MyResponse("400", ex.getMessage());
        return  Response.status(Status.BAD_REQUEST).entity(myResponse).type(MediaType.APPLICATION_JSON).build();
    }
    catch(Exception ex){
        myResponse = new MyResponse("500", ex.getMessage());
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(myResponse).type(MediaType.APPLICATION_JSON).build();
    }
}

这不起作用,测试进入save方法并导致我想避免的NullPointerException:

  @Test
  public void givenBadRequest_whenSaving_Then400() {
    // Given
    classIWantToMock = mock(ClassIWantToMock.class);

    // When
    doThrow(new BadRequestException("Bad Request")).when(classIWantToMock).save(isA(String.class), isA(String.class));
    response = underTest.myMethod(a, b);
    assertEquals(400, response.getStatus());
  }

TIA!

1 个答案:

答案 0 :(得分:1)

这里:

// Given
classIWantToMock = mock(ClassIWantToMock.class);

// When
doThrow(new BadRequestException("Bad Request")).when(classIWantToMock).save(isA(String.class), isA(String.class));
response = underTest.myMethod(a, b);

但是嘲笑一个类并不意味着所有使用该类类型声明的字段都会被嘲讽。
确实,您模拟了生成模拟实例的类,但是从未在测试的实例中设置此对象。因此,NPE是预期的。

ClassIWantToMock应该是被测类的依赖项。这样,您可以在其中设置模拟对象。
例如,您可以在构造器中设置它,例如:

ClassIWantToMock classIWantToMock = mock(ClassIWantToMock.class);
UnderTest underTest = new UnderTest(classIWantToMock);