Mockito.when thenReturn based on input parameter

Valeriy K. :

I have some code with encryption. In tests, I want to analyze the encrypted packet, decrypt and return back a result. What I want is something like:

Mockito.when(myClient.sendMessage(someEncryptedRandomMessage)).thenReturn(encrypt(decryptAndAnalyze(someEncryptedRandomMessage)));

How I can realize it?

Sergey Prokofiev :

There is thenAnswer method which can access passed parameters. Assuming that your someEncryptedRandomMessage is String it will look like this

Mockito.when(myClient.sendMessage(someEncryptedRandomMessage))
       .thenAnswer(inv -> encrypt(decryptAndAnalyze(inv.getArgumentAt(0, String.class))));

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=194475&siteId=1