• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 static org.mockito.internal.exceptions.Reporter.cannotStubVoidMethodWithAReturnValue;
8 import static org.mockito.internal.exceptions.Reporter.wrongTypeOfReturnValue;
9 
10 import java.io.Serializable;
11 
12 import org.mockito.internal.util.KotlinInlineClassUtil;
13 import org.mockito.invocation.InvocationOnMock;
14 import org.mockito.stubbing.Answer;
15 import org.mockito.stubbing.ValidableAnswer;
16 
17 public class Returns implements Answer<Object>, ValidableAnswer, Serializable {
18 
19     private static final long serialVersionUID = -6245608253574215396L;
20     private final Object value;
21 
Returns(Object value)22     public Returns(Object value) {
23         this.value = value;
24     }
25 
26     @Override
answer(InvocationOnMock invocation)27     public Object answer(InvocationOnMock invocation) throws Throwable {
28         return KotlinInlineClassUtil.unboxUnderlyingValueIfNeeded(invocation, value);
29     }
30 
31     @Override
validateFor(InvocationOnMock invocation)32     public void validateFor(InvocationOnMock invocation) {
33         InvocationInfo invocationInfo = new InvocationInfo(invocation);
34         if (invocationInfo.isVoid()) {
35             throw cannotStubVoidMethodWithAReturnValue(invocationInfo.getMethodName());
36         }
37 
38         if (returnsNull() && invocationInfo.returnsPrimitive()) {
39             throw wrongTypeOfReturnValue(
40                     invocationInfo.printMethodReturnType(), "null", invocationInfo.getMethodName());
41         }
42 
43         if (!returnsNull()
44                 && !invocationInfo.isValidReturnType(returnType())
45                 && !KotlinInlineClassUtil.isInlineClassWithAssignableUnderlyingType(
46                         returnType(), invocationInfo.getMethod().getReturnType())) {
47             throw wrongTypeOfReturnValue(
48                     invocationInfo.printMethodReturnType(),
49                     printReturnType(),
50                     invocationInfo.getMethodName());
51         }
52     }
53 
printReturnType()54     private String printReturnType() {
55         return value.getClass().getSimpleName();
56     }
57 
returnType()58     private Class<?> returnType() {
59         return value.getClass();
60     }
61 
returnsNull()62     private boolean returnsNull() {
63         return value == null;
64     }
65 
66     @Override
toString()67     public String toString() {
68         return "Returns: " + value;
69     }
70 }
71