2014-10-06 56 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來代替,可以將這些對象傳遞給構造函數,並查看構造函數是否按照您希望的方式工作。