Can I request arguments passed to a fake Mockito object?

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.

+6
source share
2 answers

Basically you need to use argThat () in Mockito, which allows you to consider the Hamcrest Matcher as a validation argument. Here is the code you use to create custom statements about the pass-in argument:

 @Test public void testname() throws Exception { HashReceiver receiver = mock(HashReceiver.class); receiver.set("hash"); verify(receiver).set(argThat(new HashMatcher())); } class HashMatcher extends BaseMatcher<String> { @Override public boolean matches(Object item) { String hash = (String) item; if (hash.startsWith("/data/inbound/XJSLGG.") && hash.endsWith(".pdf")) return true; return false; } } // Mocked class HashReceiver { public void set(String hash) { } } 

Instead, you can use common matches or a combination of common patterns.

+3
source

Take a look at the accepted answer to this question mockito-how-to-make-a-method-return-an-argument-that-was-passed-to-it , it will show you how to get the arguments passed to your mock method call.

+1
source

Source: https://habr.com/ru/post/891223/


All Articles