I am studying Mockito at the moment, and one of the things I do to consolidate my training is to convert the old JUnit test using a hand-rolled class to one that uses mocks instead of Mockito. However, I came across a situation, I am not sure how to handle it.
In particular, my test unit builds a String , which is passed to the defrauded object as a parameter in a method call on it. I would like to verify that String built correctly. The challenge is that the String part is a hash key that is created internally and changed with every call. One solution that should work would be to get the hash generation under my control and insert a dummy generator to run the test. However, this is a fair job.
My old manual class layout will keep the arguments passed to it, which I could request in my test. This allowed me to query the beginning and end of a String as follows:
assertTrue(mockFtpClient.getFilePathAndName().startsWith("/data/inbound/XJSLGG.")); assertTrue(mockFtpClient.getFilePathAndName().endsWith(".pdf"));
It was a good enough test for my taste. So my question is: is it possible to use Mockito to query or retrieve the arguments passed to the method so that I can do something like the above?
UPDATE 06/24/2011 : At the moment, I have excluded Gnon's answer. However, since then I have discovered something that works best for me. Namely ArgumentCaptor . Here's how it works:
ArgumentCaptor<String> fileNameArgument = ArgumentCaptor.forClass(String.class); verify(mockFtpClient).putFileOnServer(fileNameArgument.capture()); assertTrue(fileNameArgument.getValue().startsWith(START_FILE_NAME) && fileNameArgument.getValue().endsWith(END_FILE_NAME));
The javadoc for Mockito states that an ArgumentCaptor is generally the best choice when you have a one-time argument-matching requirement, as I am here.
source share