Unit testing: how to verify that an argument was passed to a constructor?

I have the following code on my Android application:

public Observable<Person> execute(MyObject myObject) {
    return service.execute(new MyApiRequest(myObject));
}

What I want to test, using Mockito is that the same instance of MyObject is passed to MyApiRequest constructor. Let's say we don't know how MyApiRequest looks. I only want to test that there "myObject" param from execute() method is the same as MyApiRequest recieves.

Answers


Yes, you can use an ArgumentCaptor to inspect the MyApiRequest that comes back.

// Create the object and the captor.
ArgumentCaptor<MyApiRequest> myApiRequestCaptor =
    ArgumentCaptor.forClass(MyApiRequest.class);
MyObject myObject = new MyObject();

// Run the test.
systemUnderTest.execute(myObject);

// Capture the MyApiRequest.
verify(service).execute(myApiRequestCaptor.capture());
MyApiRequest myApiRequest = myApiRequestCaptor.getValue();

// Now check the object identity.
assertSame("MyApiRequest should have the exact same passed-in object.",
    myObject, myApiRequest.getParameter());

Need Your Help

Migration Swift 3.0 - Podfile with RNCryptor and other libraries

ios swift cocoapods rncryptor

I just upgraded Swift to 3.0 and I have many problems with librairies.