KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > mockobjects > io > MockOutputStream


1 package com.mockobjects.io;
2
3 import com.mockobjects.ExpectationCounter;
4 import com.mockobjects.ExpectationValue;
5 import com.mockobjects.Verifiable;
6 import com.mockobjects.util.Verifier;
7
8 import java.io.ByteArrayOutputStream JavaDoc;
9 import java.io.IOException JavaDoc;
10 import java.io.OutputStream JavaDoc;
11
12 public class MockOutputStream extends OutputStream JavaDoc implements Verifiable {
13     private ExpectationValue myWriteWasCalled = new ExpectationValue("MockOutputStream.writeWasCalled");
14     private ExpectationCounter myCloseCalls = new ExpectationCounter("MockOutputStream.close()");
15     private ExpectationCounter myFlushCalls = new ExpectationCounter("MockOutputStream.flush()");
16     private ByteArrayOutputStream JavaDoc myBuffer = new ByteArrayOutputStream JavaDoc();
17     private boolean shouldThrowException = false;
18
19     public MockOutputStream() {
20         super();
21     }
22
23     public void clearActualBuffer() {
24         myBuffer = new ByteArrayOutputStream JavaDoc();
25     }
26
27     public void close() throws IOException JavaDoc {
28         myCloseCalls.inc();
29     }
30
31     public void flush() throws IOException JavaDoc {
32         myFlushCalls.inc();
33     }
34
35     public String JavaDoc getContents() {
36         return myBuffer.toString();
37     }
38
39     /**
40      * Added in response to Bug report 546661.
41      */

42     public byte[] getContentsAsByteArray() {
43         return myBuffer.toByteArray();
44     }
45
46     public void setExpectedCloseCalls(int closeCall) {
47         myCloseCalls.setExpected(closeCall);
48     }
49
50     public void setExpectedFlushCalls(int flushCall) {
51         myFlushCalls.setExpected(flushCall);
52     }
53
54     public void setExpectingWriteCalls(boolean expectingWriteCall) {
55         myWriteWasCalled.setExpected(expectingWriteCall);
56     }
57
58     public void setupThrowIOException(boolean throwException) {
59         shouldThrowException = throwException;
60     }
61
62     public void verify() {
63         Verifier.verifyObject(this);
64     }
65
66     public void write(int b) throws IOException JavaDoc {
67         myWriteWasCalled.setActual(true);
68         if (shouldThrowException) {
69             throw new IOException JavaDoc("Test IOException generated by request");
70         }
71         myBuffer.write(b);
72     }
73 }
74
Popular Tags