2014-10-06 69 views
1

我想涵盖此try块的catch部分与JUnit。我该怎么做?如何通过JUnit覆盖块捕获

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); 
     } 
    } 
} 
+4

使init方法抛出这些不同的错误或模拟trustManagerFactory,并使trustManagerFactory.getTrustManagers()抛出这些错误。 – StackFlowed 2014-10-06 13:38:19

回答

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