gpt4 book ai didi

java - 如何在 SSLContextBuilder.create().loadTrustMaterial 的 JUnit 测试中抛出异常?

转载 作者:行者123 更新时间:2023-12-01 19:52:29 25 4
gpt4 key购买 nike

我尝试为以下代码编写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

关于java - 如何在 SSLContextBuilder.create().loadTrustMaterial 的 JUnit 测试中抛出异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59075316/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com