MCPcopy Create free account
hub / github.com/Berkeley-CS61B/skeleton-sp23 / OutputCapture

Class OutputCapture

lab03/tests/helpers/CaptureSystemOutput.java:108–192  ·  view source on GitHub ↗

OutputCapture captures output to System.out and System.err. To obtain an instance of OutputCapture, declare a parameter of type OutputCapture in a JUnit Jupiter @Test, @BeforeEach, or @AfterEach method. To obtain all output to {

Source from the content-addressed store, hash-verified

106 * @author Sam Brannen
107 */
108 static class OutputCapture {
109
110// private final List<Matcher<? super String>> matchers = new ArrayList<>();
111
112 private CaptureOutputStream captureOut;
113
114 private CaptureOutputStream captureErr;
115
116 private ByteArrayOutputStream copy;
117
118 void captureOutput() {
119 this.copy = new ByteArrayOutputStream();
120 this.captureOut = new CaptureOutputStream(System.out, this.copy);
121 this.captureErr = new CaptureOutputStream(System.err, this.copy);
122 System.setOut(new PrintStream(this.captureOut));
123 System.setErr(new PrintStream(this.captureErr));
124 }
125
126 void releaseOutput() {
127 System.setOut(this.captureOut.getOriginal());
128 System.setErr(this.captureErr.getOriginal());
129 this.copy = null;
130 }
131
132 private void flush() {
133 try {
134 this.captureOut.flush();
135 this.captureErr.flush();
136 } catch (IOException ex) {
137 // ignore
138 }
139 }
140
141 /**
142 * Return all captured output to {@code System.out} and {@code System.err}
143 * as a single string.
144 */
145 @Override
146 public String toString() {
147 flush();
148 return this.copy.toString();
149 }
150
151 private static class CaptureOutputStream extends OutputStream {
152
153 private final PrintStream original;
154
155 private final OutputStream copy;
156
157 CaptureOutputStream(PrintStream original, OutputStream copy) {
158 this.original = original;
159 this.copy = copy;
160 }
161
162 PrintStream getOriginal() {
163 return this.original;
164 }
165

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected