如何通过JUnit覆盖块捕获

时间:2014-10-06 13:36:13

标签: java junit try-catch

我想用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);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

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