简体   繁体   English

如何在方法中模拟对象

[英]how to mock a object in method

I want to mock response object here when I call getHSMDecryptedData method from my test method. 当我从测试方法调用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

This is my test method: 这是我的测试方法:

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); 

You access the HSMService object via the Java Singleton Pattern . 您可以通过Java Singleton Pattern访问HSMService对象。 This kind of singletons are basically global variables which software developers consider being evil since the late 80s... 这种单例基本上是全局变量 ,自80年代末以来,软件开发人员就认为这是邪恶的...

You better inject the HSMService object preferably as constructor parameter or any other dependency injection technique. 最好 HSMService对象作为构造函数参数或任何其他依赖项注入技术来注入 In that case you can replace the HSMService object with a mock which in turn returns a mock of the DecryptDataResponse class on call of the processRequest method. 在那种情况下,您可以用模拟替换HSMService对象,该模拟继而在调用processRequest方法时返回DecryptDataResponse类的模拟。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM