4

I have an interface like

public interface WithMD5Calculator{

    default String getMd5(){
        try{
            MessageDigest md = MessageDigest.getInstance("MD5");
            //... not important
        }catch(NoSuchAlgorithmException e){
           //... do some extra stuff and throw wrapped in ServiceException
        }
    }

    // rest of code not important
}

And test that should verify exception handling:

@RunWith(PowerMockRunner.class)
@PrepareForTest(MessageDigest.class)
public class WithMD5Calculator{

    @Test
    public void shouldHandleNSAEx(){
        PowerMockito.mockStatic(MessageDigest.class);
        Mockito.when(MessageDigest.getInstance("MD5")).thenThrow(new NoSuchAlgorithmException("Throwed"));

        WithMD5Calculator sut = new WithMD5Calculator(){};
        ExceptionAssert.assertThat(()-> sut.getMd5())
           .shouldThrow(ServiceException.class);
        // some more checks
    }
}

But ServiceException were not throwed. Looks like MessageDigest.getInstance were not mocked.

Any idea?

Koziołek
  • 2,791
  • 1
  • 28
  • 48
  • `verify` could be useful if I want to check is method called or more general behavior of static class. In my case I don't need to verify behavior but to change behavior of method. – Koziołek Dec 08 '15 at 10:44
  • An idea: when using PowerMockito for mocking the method, you might want to use PowerMockito for stubbing the method (e.g. PowerMockito.when(...).thenThrow(...)). How is Mockito supposed to know that you invoked the static method? – xmjx Dec 08 '15 at 10:48
  • Method `when` from PowerMockito is just wrapper for `when` from Mockito library. "Magic" of PowerMockito is that it prepare class with static, by annotation `@PrepareForTest`, to be "mockable" by Mockito. – Koziołek Dec 08 '15 at 12:47
  • 2
    Powermock docs say that mocking classes loaded by the java system/bootstrap classloader is dode a bit differently: https://github.com/jayway/powermock/wiki/MockSystem. But I have not succeeded to make this approach work with Mockito. – Vladimir Korenev Dec 09 '15 at 18:58

1 Answers1

-1

Add WithMD5Calculator to PrepareForTest list may solve your problem.