Java Reference
In-Depth Information
output to the standard output; second, the output may contain extra spaces
or text in addition to the values of the operands.
Decision point
How is it possible to test a program that uses standard input and output?
The simplest solution is to redirect the standard input and output streams
( System.in and System.out ). The input can be read from a string by means
of class StringBufferInputStream . The output produced by the program can be
recorded into a string buffer by means of class ByteArrayOutputStream .
Decision point
How can we check an output containing extra blanks or text?
The option of performing an exact string match is not feasible because a
minor change in the output (addition of a single white space) would break
the test. A better option is to check the output for the presence of specific
substrings. In addition it is useful to verify that the substrings appear in a
given order within the output. In the test class TestCommand the purpose of
the method assertContainsInOrder() is to verify that the output string contains
all the elements of a string array in the correct order.
The following test class implements the first three lines of the test case
described in Table 6.4. It is the text-oriented version of the TestCalculator
test presented before.
public class TestCommand extends TestCase {
//...
public void testCommand(){
String input # "op 3.2\n" ! "op 2.8\n" !
" ! \n" ! "exit\n";
// redirect the standard input to read
// from the input string
InputStream oldIn # System.in;
System.setIn( new StringBufferInputStream(input));
// redirect the standard output to write
// into a string buffer
PrintStream oldOut # System.out;
ByteArrayOutputStream buffer #
new ByteArrayOutputStream();
System.setOut( new PrintStream(buffer));
// create a command object and run it
Command c # new Command();
c.run();
Search WWH ::




Custom Search