Java Reference
In-Depth Information
As I may have said in
Avoiding the Need for Debuggers with Unit Testing
, no code is com-
plete until it has a working test. Here is the
JUnit
test for
TextAreaWriter
:
public
public class
class
TextAreaWriterTest
TextAreaWriterTest
extends
extends
TestCase
{
private
private static
static final
final
String HELLO_WORLD
=
"Hello World"
;
JTextArea ta
=
new
new
JTextArea
();
public
public
void
void
testOne
() {
PrintWriter x
=
new
new
PrintWriter
(
new
new
TextAreaWriter
(
ta
));
x
.
print
(
"Hello"
);
x
.
print
(
' '
);
x
.
print
(
"World"
);
x
.
close
();
assertEquals
(
HELLO_WORLD
,
ta
.
getText
());
}
}
Note that my test creates a visual component but never uses it in a GUI. Because this is the
first time we've seen this technique, it's worth mentioning that it is acceptable (on all plat-
forms I've tried it) to have a
JUnit
test that creates a
Component
subclass without setting it
visible, if you only want to test methods that don't depend on actual graphics being dis-
played, as we're doing here. On Mac OS X, this may cause a brief delay because it creates a
“running Java program” icon, but it seems otherwise harmless.
The
OutputStream
case is just a tiny bit more involved, but worth doing so we can re-use
legacy code that writes to
System.out
. Here is
TextAreaOutputStream
:
package
package
com
.
darwinsys
.
io
;
import
import
java.io.IOException
java.io.IOException
;
import
import
java.io.OutputStream
java.io.OutputStream
;
import
import
javax.swing.JTextArea
javax.swing.JTextArea
;
/**
* Simple way to "print" to a JTextArea; just say
* PrintStream out = new PrintStream(new TextAreaOutputStream(myTextArea));
* Then out.println() et all will all appear in the TextArea.
*/
public
public final
final class
class
TextAreaOutputStream
TextAreaOutputStream
extends
extends
OutputStream
{