2017-05-29 92 views
1

我想在我的測試方法中調用getHSMDecryptedData方法時在此處模擬響應對象。如何在方法中模擬對象

private String getHSMDecryptedData(String keysetName, int groupIndex, 
            String ksn, String encryptedData) { 
    String decryptedData = null; 
    try { 
     DecryptData decrypt = new DecryptData(); 
     decrypt.setKeySet(keysetName); 
     decrypt.setKsnDescriptor("906"); 
     decrypt.setKsn(ksn); 
     decrypt.setKeyType(HSMKeyTypeDataModel.TYPE_BDK); 
     decrypt.setEncryptionMode(HSMEncryptionMode.CBC); 
     decrypt.setInputFormat(HSMDataFormat.HEX_ENCODED_BINARY); 
     decrypt.setOutputFormat(HSMDataFormat.HEX_ENCODED_BINARY); 
     decrypt.setMessage(encryptedData); 

     // sending M2 command to HSM for decryption of encrypted data coming from CP 
     DecryptDataResponse response = (DecryptDataResponse) HSMService.getInstance().processRequest(decrypt); 

     System.out.println(response+"***************reponse"); 
     if (response != null && response.getResponseCode() == HSMResponseCodes.APPROVED) { 
      decryptedData = response.getDecryptedMessage(); 
      TraceLog.Info(getClass(), 
       "Message decrypted[" + decryptedData + "], original input[" + encryptedData + "], replacing original encrypted data!"); 
      if (decryptedData == null) { 
      // throw new FirstadatException("Unable to get the decrypted Data from HSM "); 
      } 
     }//FirstadatException 

這是我的測試方法:

HsmDataDecrypt hsmDataDecrypt = new HsmDataDecrypt(); 
    try { 
     DecryptDataResponse response=mock(DecryptDataResponse.class); 
     //response. 
     Method method = hsmDataDecrypt.getClass().getDeclaredMethod("getHSMDecryptedData", String.class,int.class,String.class,String.class); 
+0

您可能會發現PowerMock可以解決您的問題,因爲它允許您模擬靜態方法調用。 **不要!**這是一個糟糕的解決方案,因爲你的代碼不好,所以只有這個問題。聽蒂莫西,依賴注入將很好地解決你的問題並清理你的代碼,而PowerMock只會讓你隱藏真正的問題。 –

+0

yup謝謝...... –

回答

2
DecryptDataResponse response = (DecryptDataResponse) HSMService.getInstance().processRequest(decrypt); 

您通過的Java Singleton模式訪問HSMService對象。這種單身基本都是全局變量其軟件開發人員認爲80年代末期以來被邪惡......

你最好注入HSMService物體最好的構造函數的參數或任何其他依賴注入技術。 在這種情況下,您可以用模擬替換HSMService對象,然後返回DecryptDataResponse類的模擬,並調用processRequest方法。

+0

感謝您的建議,我通過創建注入HSMService對象的構造函數進行相應的更改,現在它嘲笑響應。謝謝。 –

相關問題