我已经尝试为以下代码编写junit测试,但是无法在测试用例中引发异常。以下是实现:
public static HttpClientBuilder createTrustAllHttpClientBuilder() {
try {
SSLContext sslContext = SSLContextBuilder
.create()
.loadTrustMaterial(null, (certificate, authType) -> true)
.build();
}
catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
throw new IllegalStateException(e);
}
}
以下是我的junit测试:
@RunWith(PowerMockRunner.class)
@PrepareForTest({SSLContextBuilder.class})
public class testClass {
public void testCase() {
SSLContextBuilder sslContextBuilder = mock(SSLContextBuilder.class, RETURNS_DEEP_STUBS);
PowerMockito.mockStatic(SSLContextBuilder.class);
PowerMockito.when(SSLContextBuilder.create()).thenReturn(sslContextBuilder);
PowerMockito.when(sslContextBuilder.loadTrustMaterial(null, (certificate, authType) -> true)).thenThrow(new NoSuchAlgorithmException());
}
}
如果您之前遇到以下问题,我将非常感谢您提供的任何形式的帮助或知识共享。谢谢!
因为已经有了模拟,所以可以使用thenThrow
而不是thenReturn
使模拟抛出异常。
https://static.javadoc.io/org.mockito/mockito-core/2.2.9/org/mockito/stubbing/OngoingStubbing.html