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

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,则可以将这些对象传递到构造函数中,并查看构造函数是否按照您希望的方式工作。

10-06 14:47