如何在方法中模拟对象



当我从测试方法调用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);
DecryptDataResponse response = (DecryptDataResponse) HSMService.getInstance().processRequest(decrypt);

您可以通过 Java 单例模式访问HSMService对象。这种单例基本上是自 80 年代后期以来软件开发人员认为是邪恶的全局变量......

最好将HSMService对象作为构造函数参数或任何其他依赖项注入技术注入。在这种情况下,您可以将 HSMService 对象替换为模拟,而模拟又在调用 processRequest 方法时返回DecryptDataResponse类的模拟。

相关内容

  • 没有找到相关文章

最新更新