Java Reference
In-Depth Information
The
String
message is very helpful when you get large numbers of com-
parisons and assertions inside your test cases. It can help you identify which
assert in which test failed.
TIP
When writing your assertions, keep in mind the difference between
assertEquals()
and
assertSame()
. The latter will test if the two argu-
ments refer to the very same instance of an object, whereas the former only
checks to see that their values are equal. So any two references to objects that
are the same will also be equal, but not vice versa. For example:
String sample = "value";
String others = "more value".substring(5);
assertEquals(sample, others); // will pass
assertSame(sample, others); // will fail
Digging a little deeper into how all this works, it might be worth pointing
out that the JUnit
TestCase
class, while an abstract class itself, is also an exten-
sion of another class, the
Assert
class. The
Assert
class is the class that defines
all these public static methods for asserting the various conditions (see the list
above). That is why you don't need any qualifiers on the various assert calls.
They are all part of your test case by virtue of it extending
TestCase
. It also
means that you could override any of them to get special behavior. This might
be useful for
assertEquals(Object, Object)
, to allow you to compare
objects of your own kinds, but we don't recommend this. You are better off
overriding the
equals()
method of your own object than messing with the
JUnit methods. And remember that if you override those behaviors, your tests
will only be as good as your implementation of the assert mechanisms.
13.5.2
Recall how we ran the JUnit self-tests after installation. We can now use a
similar command to execute our own test case. With the
CLASSPATH
still set
as above, try compiling and running the test case:
Running a Test Case
$ javac net/multitool/core/AccountTest.java
$ java junit.textui.TestRunner net.multitool.core.AccountTest