• 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.mockitousage.stubbing;
6 
7 import org.junit.Test;
8 import org.mockito.Mock;
9 import org.mockitoutil.TestBase;
10 
11 import static org.junit.Assert.assertEquals;
12 import static org.mockito.Mockito.*;
13 
14 public class CallingRealMethodTest extends TestBase {
15 
16     @Mock
17     TestedObject mock;
18 
19     static class TestedObject {
20 
21         String value;
22 
setValue(String value)23         void setValue(String value) {
24             this.value = value;
25         }
26 
getValue()27         String getValue() {
28             return "HARD_CODED_RETURN_VALUE";
29         }
30 
callInternalMethod()31         String callInternalMethod() {
32             return getValue();
33         }
34     }
35 
36     @Test
shouldAllowCallingInternalMethod()37     public void shouldAllowCallingInternalMethod() {
38         when(mock.getValue()).thenReturn("foo");
39         when(mock.callInternalMethod()).thenCallRealMethod();
40 
41         assertEquals("foo", mock.callInternalMethod());
42     }
43 
44     @Test
shouldReturnRealValue()45     public void shouldReturnRealValue() {
46         when(mock.getValue()).thenCallRealMethod();
47 
48         assertEquals("HARD_CODED_RETURN_VALUE", mock.getValue());
49     }
50 
51     @Test
shouldExecuteRealMethod()52     public void shouldExecuteRealMethod() {
53         doCallRealMethod().when(mock).setValue(anyString());
54 
55         mock.setValue("REAL_VALUE");
56 
57         assertEquals("REAL_VALUE", mock.value);
58     }
59 
60     @Test
shouldCallRealMethodByDefault()61     public void shouldCallRealMethodByDefault() {
62         TestedObject mock = mock(TestedObject.class, CALLS_REAL_METHODS);
63 
64         assertEquals("HARD_CODED_RETURN_VALUE", mock.getValue());
65     }
66 
67     @Test
shouldNotCallRealMethodWhenStubbedLater()68     public void shouldNotCallRealMethodWhenStubbedLater() {
69         TestedObject mock = mock(TestedObject.class);
70 
71         when(mock.getValue()).thenCallRealMethod();
72         when(mock.getValue()).thenReturn("FAKE_VALUE");
73 
74         assertEquals("FAKE_VALUE", mock.getValue());
75     }
76 }
77