Argument matching when equals() cannot be used.

856 views
Skip to first unread message

Marcel Overdijk

unread,
Jan 11, 2010, 5:48:27 AM1/11/10
to mockito
I like to test some argument matching. My argument's class is 3th
party class but the equals method does not work, so it cannot match
the argument.

How can I solve this. I was reading about hamcrest but can't see the
light (yet).

Any pointer to a code example would be helpful.

This the argument I'm talking about:
http://code.google.com/intl/nl/appengine/docs/java/javadoc/com/google/appengine/api/urlfetch/HTTPRequest.html
when(urlFetchService.fetch(httpRequest).thenReturn(httpResponse);


Cheers,
Marcel

Marcel Overdijk

unread,
Jan 11, 2010, 8:20:07 AM1/11/10
to mockito
To answer my own question: I used the ArgumentMatcher to create a
custom matcher as seen below.
I called in my test like: when(urlFetchService.fetch(matchesRequest
(url, HTTPMethod.GET))).thenReturn(httpResponse);

package com.footdex.test.appengine.api.urlfetch;

import static org.mockito.Matchers.argThat;
import java.net.URL;
import org.mockito.ArgumentMatcher;
import com.google.appengine.api.urlfetch.HTTPMethod;
import com.google.appengine.api.urlfetch.HTTPRequest;

public class HTTPRequestMatcher extends ArgumentMatcher<HTTPRequest> {

URL url;
HTTPMethod method;

public HTTPRequestMatcher(URL url, HTTPMethod method) {
this.url = url;
this.method = method;
}

@Override
public boolean matches(Object argument) {
HTTPRequest request = (HTTPRequest)argument;
return request.getURL().equals(url) && request.getMethod
().equals(method);
}

public static HTTPRequest matchesRequest(URL url, HTTPMethod
method) {
return argThat(new HTTPRequestMatcher(url, method));
}
}

szczepiq

unread,
Jan 11, 2010, 7:06:35 PM1/11/10
to moc...@googlegroups.com
Hi,

For stubbing purposes: If equals() arg matching don't work you can:
- implement a matcher (as you did)
- relax the stubbing and use 'any()' argument matcher

For verification you can also use ArgumentCaptor to capture args for
future verifications.

Hope that helps!
Cheers,
Szczepan Faber

> --
> You received this message because you are subscribed to the Google Groups "mockito" group.
> To post to this group, send email to moc...@googlegroups.com.
> To unsubscribe from this group, send email to mockito+u...@googlegroups.com.
> For more options, visit this group at http://groups.google.com/group/mockito?hl=en.
>
>
>
>

Marcel Overdijk

unread,
Jan 12, 2010, 3:04:52 AM1/12/10
to mockito
Thanks Szczepan,

As you have seen above I already implemented the custom matcher.
I needed this as I wanted to test that some specific argument values
were passed to my mock, so any() was not sufficient.


Cheers,
Marcel

Reply all
Reply to author
Forward
0 new messages