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