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