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