gpt4 book ai didi

java - 如何通过 JUnit 覆盖 block 捕获

转载 作者:太空宇宙 更新时间:2023-11-04 14:30:34 25 4
gpt4 key购买 nike

我想用 JUnit 覆盖此 try block 的 catch 部分。我该怎么做?

public class ClientCertSocketFactory implements SecureProtocolSocketFactory {
private static final Logger LOGGER = LoggerFactory.getLogger(ClientCertSocketFactory.class);

private SSLSocketFactory sslSocketFactory;

public ClientCertSocketFactory() throws IOException{
String trustStoreFilePath = System.getProperty("javax.net.ssl.trustStore");
try {
TrustManagerFactory trustManagerFactory = CertManagerFactory.loadTrustStore(trustStoreFilePath);
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
this.sslSocketFactory = sslContext.getSocketFactory();
} catch (NoSuchAlgorithmException e) {
LOGGER.error("No Provider supports a TrustManagerFactorySpi implementation for the TLS protocol. Error message: " + e);
} catch (KeyManagementException e) {
LOGGER.error("Error occurred when initializing SSLContext. Error message: " + e);
}
}
}

最佳答案

First of all, catching exceptions and doing nothing but logging them is a Code Smell. Read this article, for example.

话虽这么说,当您调用这些创建方法时,它有一种代码气味:

  • CertManagerFactory.loadTrustStore
  • SSLContext.getInstance

在构造函数内部,而不是将它们传入。如果您要使用 Dependency Injection相反,您可以将这些对象传递到构造函数中,然后查看构造函数是否按您希望的方式工作。

关于java - 如何通过 JUnit 覆盖 block 捕获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26217434/

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