View Javadoc
1   /*
2    * MIT License
3    * Copyright (c) 2006-2025 JMockit developers
4    * See LICENSE file for full license text.
5    */
6   package otherTests.testng;
7   
8   import static org.testng.Assert.assertNotNull;
9   import static org.testng.Assert.assertTrue;
10  import static org.testng.Assert.fail;
11  
12  import java.io.BufferedWriter;
13  import java.io.IOException;
14  
15  import mockit.Capturing;
16  import mockit.Expectations;
17  import mockit.Injectable;
18  import mockit.Mocked;
19  
20  import org.testng.annotations.BeforeMethod;
21  import org.testng.annotations.Test;
22  
23  public final class TestNGSharedMockFieldTest {
24      public interface Dependency {
25          boolean doSomething();
26  
27          void doSomethingElse();
28      }
29  
30      @Mocked
31      Dependency mock1;
32      @Capturing
33      Runnable mock2;
34      @Injectable
35      BufferedWriter writer;
36  
37      @Test
38      public void recordAndReplayExpectationsOnSharedMocks() {
39          new Expectations() {
40              {
41                  mock1.doSomething();
42                  result = true;
43                  mock2.run();
44              }
45          };
46  
47          assertTrue(mock1.doSomething());
48          mock2.run();
49      }
50  
51      @Test
52      public void recordAndReplayExpectationsOnSharedMocksAgain() {
53          new Expectations() {
54              {
55                  mock1.doSomething();
56                  result = true;
57              }
58          };
59  
60          assertTrue(mock1.doSomething());
61          mock2.run();
62      }
63  
64      @BeforeMethod
65      public void preventAllWritesToMockedBufferedWritersFromSUT() throws Exception {
66          new Expectations() {
67              {
68                  writer.write(anyString, anyInt, anyInt);
69                  result = new IOException();
70                  minTimes = 0;
71              }
72          };
73      }
74  
75      @Test
76      public void useMockedBufferedWriter() throws Exception {
77          writer.newLine();
78  
79          try {
80              writer.write("test", 0, 4);
81              fail();
82          } catch (IOException ignore) {
83          }
84      }
85  
86      public static class Collaborator {
87      }
88  
89      public interface BaseType {
90          Collaborator doSomething();
91      }
92  
93      public interface SubType extends BaseType {
94      }
95  
96      @Mocked
97      SubType mock;
98  
99      @Test
100     public void cascadeFistTime() {
101         Collaborator cascaded = mock.doSomething();
102         assertNotNull(cascaded);
103     }
104 
105     @Test
106     public void cascadeSecondTime() {
107         Collaborator cascaded = mock.doSomething();
108         assertNotNull(cascaded);
109     }
110 }