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 ; 9 import java.io.IOException ; 10 import java.io.OutputStream ; 11 12 public class MockOutputStream extends OutputStream 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 myBuffer = new ByteArrayOutputStream (); 17 private boolean shouldThrowException = false; 18 19 public MockOutputStream() { 20 super(); 21 } 22 23 public void clearActualBuffer() { 24 myBuffer = new ByteArrayOutputStream (); 25 } 26 27 public void close() throws IOException { 28 myCloseCalls.inc(); 29 } 30 31 public void flush() throws IOException { 32 myFlushCalls.inc(); 33 } 34 35 public String getContents() { 36 return myBuffer.toString(); 37 } 38 39 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 { 67 myWriteWasCalled.setActual(true); 68 if (shouldThrowException) { 69 throw new IOException ("Test IOException generated by request"); 70 } 71 myBuffer.write(b); 72 } 73 } 74 | Popular Tags |