001 /*
002 * Created on Jun 28, 2004
003 *
004 * To change the template for this generated file go to
005 * Window - Preferences - Java - Code Generation - Code and Comments
006 */
007 package biz.xsoftware.examples.behavior;
008
009 import java.io.IOException;
010 import java.nio.ByteBuffer;
011
012 import junit.framework.TestCase;
013 import biz.xsoftware.mock.CloningBehavior;
014 import biz.xsoftware.mock.MockObject;
015 import biz.xsoftware.mock.MockObjectFactory;
016
017 /**
018 * JUnit Suite of TestCases for demonstrating mocking out socket
019 * interfaces to test network failures.
020 *
021 * @author Dean Hiller
022 */
023 public class TestExample extends TestCase {
024
025 private MockObject mockSocket;
026 private TCPSocket tcpSocket;
027
028 /**
029 * @showcode
030 */
031 public TestExample(String name) {
032 super(name);
033 }
034 /**
035 * @showcode
036 */
037 public void setUp() throws Exception {
038 mockSocket = MockObjectFactory.createMock(TCPSocket.class);
039 tcpSocket = (TCPSocket)mockSocket;
040 }
041 /**
042 * @showcode
043 */
044 public void tearDown() throws IOException {
045
046 }
047
048 /**
049 * Test that upon network problems like IOException when writing to server
050 * that other subsystems get cleaned up properly. The simple test below
051 * shows how this can be done and extended to more complicated network
052 * recovery algorithms.
053 * @throws IOException
054 *
055 * @showcode
056 */
057 public void testNetworkProblems() throws IOException {
058
059 mockSocket.addBehavior("write", new MyBehavior());
060
061 byte[] data = new byte[] { 1, 2, 3, 4 };
062 ByteBuffer b = ByteBuffer.allocate(100);
063 b.put(data);
064 b.flip();
065
066 tcpSocket.write(b);
067
068 //now, our mockobject better have simulated what a real tcpSocket would do...
069 assertEquals(0, b.remaining());
070
071 //now the param passed to the mockobject better be what we passed.....
072 ByteBuffer b2 = (ByteBuffer) mockSocket.expect("write").getAllParams()[0];
073 byte[] actual = new byte[4];
074 b2.get(actual);
075
076 assertEquals(data.length, actual.length);
077 for(int i = 0; i < actual.length; i++) {
078 assertEquals(data[i], actual[i]);
079 }
080 }
081
082 private class MyBehavior implements CloningBehavior {
083 public Object[] writeCloner(ByteBuffer b) {
084 ByteBuffer clone = ByteBuffer.allocate(b.capacity());
085 clone.put(b);
086
087 //rewind original buffer so it appears not have been modified by
088 //cloning method....
089 b.rewind();
090
091 //flip the clone and it will match the given buffer exactly....
092 clone.flip();
093
094 //return the clone
095 return new Object[] { clone };
096 }
097
098 public int write(ByteBuffer b) {
099 //simulate the ByteBuffer being read....
100 int remaining = b.remaining();
101 byte[] data = new byte[remaining];
102 b.get(data);
103
104 return remaining;
105 }
106 }
107 }
|