PowerMockito无法模拟MessageDigest.getInstance()引发异常

时间:2018-09-07 08:13:40

标签: powermockito message-digest

试图获取MessageDigest.getInstance()以引发NoSuchAlgorithmException。一切似乎都是正确的,但不会抛出异常。使用DatatypeFactory.newInstance()测试类似的东西会成功引发DatatypeConfigurationException。

DatatypeFactory和MessageDigest都是“公共抽象”类,被调用的方法都是“公共静态”,所以我不知道为什么MessageDigest.getInstance()不会给我例外。

有什么想法吗?

可测试的方法(MessageDigest)

@UtilityClass
public final class HashHelper {

  public static void messageDigest() throws NoSuchAlgorithmException {
    MessageDigest.getInstance("SHA-256");
  }
}

测试类(MessageDigest)

@RunWith(PowerMockRunner.class)
@PrepareForTest({MessageDigest.class})
public class HashHelperTest {
  @Rule
  public final ExpectedException thrown = ExpectedException.none();

  @Test
  public void shouldThrowNoSuchAlgorithmException() throws NoSuchAlgorithmException {
    PowerMockito.mockStatic(MessageDigest.class);
    PowerMockito.when(MessageDigest.getInstance(any())).thenThrow(new NoSuchAlgorithmException());
    thrown.expect(NoSuchAlgorithmException.class);
    HashHelper.messageDigest();
  }
}

可测试的方法,正在运行(DatatypeFactory)

@UtilityClass
public final class SoapHelper {

  public static void dataTypeInstance() throws DatatypeConfigurationException {
    DatatypeFactory.newInstance();
  }
}

工作正常的测试类(DatatypeFactory)

@RunWith(PowerMockRunner.class)
@PrepareForTest({DatatypeFactory.class})
public class SoapHelperTest {
  @Rule
  public final ExpectedException thrown = ExpectedException.none();

  @Test
  public void shouldTrhowDatatypeConfigurationException() throws DatatypeConfigurationException {
    PowerMockito.mockStatic(DatatypeFactory.class);
    PowerMockito.when(DatatypeFactory.newInstance()).thenThrow(new DatatypeConfigurationException());
    thrown.expect(DatatypeConfigurationException.class);
    SoapHelper.dataTypeInstance();
  }
}

0 个答案:

没有答案