1 /* 2 * Copyright (c) 2007 Mockito contributors 3 * This program is made available under the terms of the MIT License. 4 */ 5 package org.mockito.internal.stubbing.answers; 6 7 import java.lang.reflect.Method; 8 import java.lang.reflect.Modifier; 9 10 import org.mockito.internal.invocation.AbstractAwareMethod; 11 import org.mockito.internal.util.MockUtil; 12 import org.mockito.internal.util.Primitives; 13 import org.mockito.internal.util.reflection.GenericMetadataSupport; 14 import org.mockito.invocation.InvocationOnMock; 15 import org.mockito.mock.MockCreationSettings; 16 17 public class InvocationInfo implements AbstractAwareMethod { 18 19 private final Method method; 20 private final InvocationOnMock invocation; 21 InvocationInfo(InvocationOnMock theInvocation)22 public InvocationInfo(InvocationOnMock theInvocation) { 23 this.method = theInvocation.getMethod(); 24 this.invocation = theInvocation; 25 } 26 isValidException(Throwable throwable)27 public boolean isValidException(Throwable throwable) { 28 Class<?>[] exceptions = method.getExceptionTypes(); 29 Class<?> throwableClass = throwable.getClass(); 30 for (Class<?> exception : exceptions) { 31 if (exception.isAssignableFrom(throwableClass)) { 32 return true; 33 } 34 } 35 36 return false; 37 } 38 isValidReturnType(Class<?> clazz)39 public boolean isValidReturnType(Class<?> clazz) { 40 if (method.getReturnType().isPrimitive() || clazz.isPrimitive()) { 41 return Primitives.primitiveTypeOf(clazz) 42 == Primitives.primitiveTypeOf(method.getReturnType()); 43 } else { 44 return method.getReturnType().isAssignableFrom(clazz); 45 } 46 } 47 48 /** 49 * Returns {@code true} is the return type is {@link Void} or represents the pseudo-type to the keyword {@code void}. 50 * E.g: {@code void foo()} or {@code Void bar()} 51 */ isVoid()52 public boolean isVoid() { 53 final MockCreationSettings mockSettings = 54 MockUtil.getMockHandler(invocation.getMock()).getMockSettings(); 55 Class<?> returnType = 56 GenericMetadataSupport.inferFrom(mockSettings.getTypeToMock()) 57 .resolveGenericReturnType(this.method) 58 .rawType(); 59 return returnType == Void.TYPE || returnType == Void.class; 60 } 61 printMethodReturnType()62 public String printMethodReturnType() { 63 return method.getReturnType().getSimpleName(); 64 } 65 getMethodName()66 public String getMethodName() { 67 return method.getName(); 68 } 69 returnsPrimitive()70 public boolean returnsPrimitive() { 71 return method.getReturnType().isPrimitive(); 72 } 73 getMethod()74 public Method getMethod() { 75 return method; 76 } 77 isDeclaredOnInterface()78 public boolean isDeclaredOnInterface() { 79 return method.getDeclaringClass().isInterface(); 80 } 81 82 @Override isAbstract()83 public boolean isAbstract() { 84 return (method.getModifiers() & Modifier.ABSTRACT) != 0; 85 } 86 } 87