Calling static mock method in default method in java 8 interface

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 a test that should check for 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 ServiceExceptionthey were not thrown away. It seems MessageDigest.getInstancethey did not scoff.

Any idea?

+4
source share
1 answer

Adding a WithMD5Calculator list to PrepareForTest may solve your problem.

0
source

Source: https://habr.com/ru/post/1619016/


All Articles