Continuing the theme of testing with gwtmockito, I’d like to show you a neat class that’s bundled with gwtmockito that allows for easy mocking of GWT-RPC asynchronous services.

The class I’m talking about is AsyncAnswers. It’s meant to be used with the doAnswer stubber.

Supposing we have a LoginServiceAsync class:

Assuming service is a mock for LoginServiceAsync, we could simulate a successful trip to the server with:

Similarly, we can simulate that a failure occurred:

Everything should be working, but that line is a bit too long. For starters, we can import static AsyncAnswers. But the biggest sore in the eye is the any() call. We need to explicitly set the type parameters, and for that to happen we can’t rely on static imports - we have to use the Matchers class directly. Let’s fix that by introducing a new ArgumentMatcher:

Now, to use it like any or anyCollection, put this method somewhere, like in your base test class:

We pass around that <T> and Class<T> for type safety - no need for casts or @SuppressWarnings. Now it looks less verbose and more to the point:

Happy testing!