Search code examples
javaunit-testingjunitmockitopowermockito

PowerMockito how to capture a parameter passed to a mock object?


I'm trying to capture a parameter passed in input to a mock object with PowerMockito, this is the code:

//I create a mock object
ClassMocked mock = PowerMockito.mock(ClassMocked.class);

//Create the captor that will capture the String passed in input to the mock object
ArgumentCaptor<String> argumentCaptor = ArgumentCaptor.forClass(String.class);

//When the method put is executed on my mock I want the second parameter (that is a String) to be captured
Mockito.verify(mock).put(anyString(), inputDataMapCaptor.capture());

//Creates the instance of the class that I want to test passing the mock as parameter
ClassToTest instance = new ClassToTest(mock);

//Executes the method that I want to test
instance.methodToTest();

/* I know that during the execution of "methodToTest()" mock.put(String,String) will be executed and I want to get the second string parameter. */

When I execute the test I have an exception executing the line Mockito.verify(mock).put(...);

"Wanted but not invoked mock.put(any,Capturing argument);"

What is wrong?


Solution

  • You should call instance.methodToTest(); before Mockito.verify(mock).put(anyString(), inputDataMapCaptor.capture());