1 /*
2  * Copyright (C) 2016 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.server.wifi;
18 
19 import org.mockito.invocation.InvocationOnMock;
20 import org.mockito.stubbing.Answer;
21 
22 import java.lang.reflect.InvocationTargetException;
23 import java.lang.reflect.Method;
24 import java.util.Arrays;
25 
26 /**
27  * Utilities for creating Answers for mock objects
28  */
29 public class MockAnswerUtil {
30 
31     /**
32      * Answer that calls the method in the Answer called "answer" that matches the type signature of
33      * the method being answered. An error will be thrown at runtime if the signature does not match
34      * exactly.
35      */
36     public static class AnswerWithArguments implements Answer<Object> {
37         @Override
answer(InvocationOnMock invocation)38         public final Object answer(InvocationOnMock invocation) throws Throwable {
39             Method method = invocation.getMethod();
40             try {
41                 Method implementation = getClass().getMethod("answer", method.getParameterTypes());
42                 if (!implementation.getReturnType().equals(method.getReturnType())) {
43                     throw new RuntimeException("Found answer method does not have expected return "
44                             + "type. Expected: " + method.getReturnType() + ", got "
45                             + implementation.getReturnType());
46                 }
47                 Object[] args = invocation.getArguments();
48                 try {
49                     return implementation.invoke(this, args);
50                 } catch (IllegalAccessException e) {
51                     throw new RuntimeException("Error invoking answer method", e);
52                 } catch (InvocationTargetException e) {
53                     throw e.getCause();
54                 }
55             } catch (NoSuchMethodException e) {
56                 throw new RuntimeException("Could not find answer method with the expected args "
57                         + Arrays.toString(method.getParameterTypes()), e);
58             }
59         }
60     }
61 
62 }
63