001 /*
002 * Copyright 2013 Google Inc.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
005 * use this file except in compliance with the License. You may obtain a copy of
006 * the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
012 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
013 * License for the specific language governing permissions and limitations under
014 * the License.
015 */
016 package com.google.gwtmockito;
017
018 import com.google.gwt.user.client.rpc.AsyncCallback;
019
020 import org.mockito.invocation.InvocationOnMock;
021 import org.mockito.stubbing.Answer;
022
023 /**
024 * A collection of answers useful for testing asynchronous GWT applications.
025 *
026 * @see Answer
027 * @author ekuefler@google.com (Erik Kuefler)
028 */
029 public class AsyncAnswers {
030
031 /**
032 * Invokes {@link AsyncCallback#onSuccess} on the first argument of type {@link AsyncCallback}
033 * passed to the method. The method must take an {@link AsyncCallback} parameter of the
034 * appropriate type.
035 *
036 * @param result argument to pass to onSuccess
037 * @return an answer that invokes onSuccess with the given argument
038 */
039 public static <T> Answer<Void> returnSuccess(final T result) {
040 return new Answer<Void>() {
041 @Override
042 @SuppressWarnings("unchecked")
043 public Void answer(InvocationOnMock invocation) {
044 for (Object arg : invocation.getArguments()) {
045 if (arg instanceof AsyncCallback<?>) {
046 ((AsyncCallback<T>) arg).onSuccess(result);
047 return null;
048 }
049 }
050 throw new IllegalStateException(
051 "returnSuccess can only be used for methods that take an AsyncCallback as a parameter");
052 }
053 };
054 }
055
056 /**
057 * Invokes {@link AsyncCallback#onFailure} on the first argument of type {@link AsyncCallback}
058 * passed to the method. The method must take an {@link AsyncCallback} parameter of the
059 * appropriate type.
060 *
061 * @param result argument to pass to onFailure
062 * @return an answer that invokes onFailure with the given argument
063 */
064 public static Answer<Void> returnFailure(final Throwable result) {
065 return new Answer<Void>() {
066 @Override
067 public Void answer(InvocationOnMock invocation) {
068 for (Object arg : invocation.getArguments()) {
069 if (arg instanceof AsyncCallback<?>) {
070 ((AsyncCallback<?>) arg).onFailure(result);
071 return null;
072 }
073 }
074 throw new IllegalStateException(
075 "returnFailure can only be used for methods that take an AsyncCallback as a parameter");
076 }
077 };
078 }
079 }