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

Java Mockito模拟一个void方法并抛出异常,而不执行方法代码,java,junit,mockito,Java,Junit,Mockito,我想模拟一个可以返回不同类型异常的void方法。我不想执行实际的方法。我只想在我的回复中看到正确的代码 public Response myMethod(String a, String b){ MyResponse myresponse; try{ classIWantToMock.save(a,b); myResponse = new MyResponse("200", SUCCESSFUL_OPERATION); r

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

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());
  }
蒂亚

这里:

// 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);

谢谢,我不知道如何进行欠测试(classIWantToMock),因为它们不相关。是什么阻止您创建/添加此构造函数的参数?