Search code examples
exceptionjunitmockitothrow

Mockito.doThrow().when .... Not working well


I'm working with JUnit and Mockito to make some unitary tests. I want to handle the excepcion by using the Mockito.doThrow() and I've already made use of it in another tests and it worked the finest way possible. Now I have:

Assigned newAssigned  = new Assigned();

      Mockito.doThrow(new SdkFault()).when(Api).addLicenseAssigned("2144", newAssigned  );

and when I run the test while making debugging of it when I find this

   Api.addLicenseAssinged(licenseId, newAssigned);

It should get the excepcion and throw it me right? Or am I making something wrong? And I'm not mocking static methods.


Solution

  • I think your issue is the stubbing you are using is trying to match against an object you have created in your test and so it is not the same object that is called in your class under test, namely:

    Assigned newAssigned  = new Assigned();
    

    To solve this you should use matchers instead for your stubbing i.e.:

    Mockito.doThrow(new SdkFault()).when(Api)
       .addLicenseAssigned(Matchers.eq("2144"), Matchers.any(Assigned.class));