[英]How to test if multiple lines of code throw an exception in junit4 Java
[英]How to throw exception in JUnit Test for SSLContextBuilder.create().loadTrustMaterial?
我嘗試為以下代碼編寫junit測試,但無法在測試用例中引發異常。 以下是實現:
public static HttpClientBuilder createTrustAllHttpClientBuilder() {
try {
SSLContext sslContext = SSLContextBuilder
.create()
.loadTrustMaterial(null, (certificate, authType) -> true) <= How to throw exception for this line
.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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.