user2572526
user2572526

Reputation: 1279

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?

Upvotes: 3

Views: 4818

Answers (2)

GhostCat
GhostCat

Reputation: 140523

verify() verifies that the specified method call did take place.

You can't verify "upfront" that a method call is supposed to happen.

Thus: verify() needs to happen after the facts, not before!

Upvotes: 1

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

Upvotes: 2

Related Questions