-
Notifications
You must be signed in to change notification settings - Fork 4
/
MockInOut.java
99 lines (89 loc) · 2.83 KB
/
MockInOut.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package fi.helsinki.cs.tmc.edutestutils;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
/**
* A simple class for capturing {@code System.out} and injecting
* {@code System.in}.
*
* <p>Usage:</p>
*
* <code>
* public void myTest() {<br>
* MockInOut mio = new MockInOut("input goes here");<br>
* try {<br>
* // Call some code<br>
* String out = mio.getOutput();<br>
* } finally {<br>
* mio.close();<br>
* }<br>
* // Check that the output is correct<br>
* }<br>
* </code>
*
* This class automatically converts line endings in stdout to unix format (only
* \n).
*
* @see MockStdio
*/
public class MockInOut {
private PrintStream orig;
private InputStream irig;
private ByteArrayOutputStream os;
private ByteArrayInputStream is;
private final static Charset charset;
static {
// Our source and tests files are UTF-8, so we assert against UTF-8 strings
// and don't want MockInOut to convert to the native charset.
if (Charset.availableCharsets().containsKey("UTF-8")) {
charset = Charset.forName("UTF-8");
} else {
charset = Charset.defaultCharset();
}
}
public MockInOut(String input) {
orig = System.out;
irig = System.in;
os = new ByteArrayOutputStream();
try {
System.setOut(new PrintStream(os, false, charset.name()));
} catch (UnsupportedEncodingException ex) {
throw new RuntimeException(ex);
}
is = new ByteArrayInputStream(input.getBytes());
System.setIn(is);
}
/**
* You can use this if you want to check how much of the input was read.
*/
public ByteArrayInputStream getInputStream() {
return is;
}
/**
* Returns everything written to System.out since this {@code MockInOut} was
* constructed. Can't be called on a closed {@code MockInOut}
*/
public String getOutput() {
if (os != null) {
try {
return os.toString(charset.name()).replace("\r\n", "\n");
} catch (UnsupportedEncodingException ex) {
throw new RuntimeException(ex);
}
} else {
throw new Error("getOutput on closed MockInOut!");
}
}
/**
* Restores System.in and System.out
*/
public void close() {
os = null;
is = null;
System.setOut(orig);
System.setIn(irig);
}
}