1

I want to mock response object here when I call getHSMDecryptedData method from my test method.

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); 
1
  • You will probably find that PowerMock could solve your problem, since it allows you to mock static method calls. Don't! It's a bad solution for a problem you only have because your code is bad. Listen to Timothy, dependency injection will solve your problem and clean up your code nicely, while PowerMock will only allow you to hide the true problem. Commented May 30, 2017 at 13:17

1 Answer 1

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

You access the HSMService object via the Java Singleton Pattern. This kind of singletons are basically global variables which software developers consider being evil since the late 80s...

You better inject the HSMService object preferably as constructor parameter or any other dependency injection technique. 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.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks for your suggestion , i have made changes accordingly by create a constructor that injecting the HSMService object , now its mocking the response. thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.