Disclaimer, I am an iOS developer that has been playing around with encryption on Android. As it stands I've managed to achieve encryption in Android but I'm asking myself how would one unit test for encryption and decryption of data?
Now the first idea that comes to mind would be something like:
String encryptedInputData = encryptedInputData("Hello");
String decryptedData = decryptData(encryptedInputData);
Assert.assertEquals(decryptedData,"Hello");
This test however poses one flaw... If something did change in the encryptedInputData
and decryptData
methods, this test would not tells what changed and why it is now breaking. So I would like to write far more granular tests. So for example given this code:
Cipher cipher = Cipher.getInstance("RSA/ECB/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] data = cipher.doFinal(message);
I'd like to make sure that the cipher
variable is using the RSA algorithm in ECB mode with no padding. I'd like to test that the message
in the .doFinal(message)
follows a particular format etc.
Now I would imagine I would be able to mock the Cipher
class, the problem here is that the encryption and decryption that was written, serves only as a Util class and to be able to unit test this, I would have to pass the mock Cipher
into the code, which given that this is a Util class seems like it would get messy i.e. I would have to either create an init method just for unit testing purposes or create setter methods just to unit test this. Which would allow me to unit test the code but then the Util class gets clunky with code that I actually don't need for production purposes.
Are there any elegant ways of being able to unit test scenarios like this? i.e. encryptedInputData
and decryptData
are public methods but these methods use various private methods which frankly need to be unit tested, the issue then is how?