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

标签 java aem junit5

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

相关文章:

java - Swing 组件不显示泰文字符

java - Mule 错误,只有所有者线程可以写入 http 模块仍然发生的消息

java - 进行 Junit 测试时,如何在 AEM Sling 模型中的节点对象中 setProperty()?

AEM 中的 OSGi 容器和应用程序服务器容器

java - 如何模拟 JPA 存储库以将其用于 Junit 测试?

java - .zip 方法中的 Observable 数量是否有限制?

java - Apache POI : Indexed Color from AWT Color input

aem - CQ/AEM Dispatcher 不刷新二进制文件

java - 从 @RunWith 过渡到 @ExtendWith

java - JUnit 5 中的类级测试注解