1 | |
|
2 | |
|
3 | |
|
4 | |
|
5 | |
|
6 | |
|
7 | |
package biz.xsoftware.examples.behavior; |
8 | |
|
9 | |
import java.io.IOException; |
10 | |
import java.nio.ByteBuffer; |
11 | |
|
12 | |
import junit.framework.TestCase; |
13 | |
import biz.xsoftware.mock.CloningBehavior; |
14 | |
import biz.xsoftware.mock.MockObject; |
15 | |
import biz.xsoftware.mock.MockObjectFactory; |
16 | |
|
17 | |
|
18 | |
|
19 | |
|
20 | |
|
21 | |
|
22 | |
|
23 | |
public class TestExample extends TestCase { |
24 | |
|
25 | |
private MockObject mockSocket; |
26 | |
private TCPSocket tcpSocket; |
27 | |
|
28 | |
|
29 | |
|
30 | |
|
31 | |
public TestExample(String name) { |
32 | 1 | super(name); |
33 | 1 | } |
34 | |
|
35 | |
|
36 | |
|
37 | |
public void setUp() throws Exception { |
38 | 1 | mockSocket = MockObjectFactory.createMock(TCPSocket.class); |
39 | 1 | tcpSocket = (TCPSocket)mockSocket; |
40 | 1 | } |
41 | |
|
42 | |
|
43 | |
|
44 | |
public void tearDown() throws IOException { |
45 | |
|
46 | 1 | } |
47 | |
|
48 | |
|
49 | |
|
50 | |
|
51 | |
|
52 | |
|
53 | |
|
54 | |
|
55 | |
|
56 | |
|
57 | |
public void testNetworkProblems() throws IOException { |
58 | |
|
59 | 1 | mockSocket.addBehavior("write", new MyBehavior()); |
60 | |
|
61 | 1 | byte[] data = new byte[] { 1, 2, 3, 4 }; |
62 | 1 | ByteBuffer b = ByteBuffer.allocate(100); |
63 | 1 | b.put(data); |
64 | 1 | b.flip(); |
65 | |
|
66 | 1 | tcpSocket.write(b); |
67 | |
|
68 | |
|
69 | 1 | assertEquals(0, b.remaining()); |
70 | |
|
71 | |
|
72 | 1 | ByteBuffer b2 = (ByteBuffer) mockSocket.expect("write").getAllParams()[0]; |
73 | 1 | byte[] actual = new byte[4]; |
74 | 1 | b2.get(actual); |
75 | |
|
76 | 1 | assertEquals(data.length, actual.length); |
77 | 5 | for(int i = 0; i < actual.length; i++) { |
78 | 4 | assertEquals(data[i], actual[i]); |
79 | |
} |
80 | 1 | } |
81 | |
|
82 | 2 | private class MyBehavior implements CloningBehavior { |
83 | |
public Object[] writeCloner(ByteBuffer b) { |
84 | 1 | ByteBuffer clone = ByteBuffer.allocate(b.capacity()); |
85 | 1 | clone.put(b); |
86 | |
|
87 | |
|
88 | |
|
89 | 1 | b.rewind(); |
90 | |
|
91 | |
|
92 | 1 | clone.flip(); |
93 | |
|
94 | |
|
95 | 1 | return new Object[] { clone }; |
96 | |
} |
97 | |
|
98 | |
public int write(ByteBuffer b) { |
99 | |
|
100 | 1 | int remaining = b.remaining(); |
101 | 1 | byte[] data = new byte[remaining]; |
102 | 1 | b.get(data); |
103 | |
|
104 | 1 | return remaining; |
105 | |
} |
106 | |
} |
107 | |
} |