Java Reference
In-Depth Information
unexpected or untested-for condition. That's all there is to it. You could get by
with a simple boolean test, but to make things easy, there are convenience meth-
ods for testing all sorts of common conditions. There are also methods that
include a message parameter, which is reported back to the user when a failure
occurs. Here are some of the assertion methods you're likely to use:
■
assertEquals(String
message,
int
expected,
int
actual)
■
assertTrue(String
message,
boolean
condition)
■
assertNotNull(Object
object)
If you look at the
JU
nit
API
, you'll see that there are assertion methods that accept
Object
s,
String
s, and all the primitives as well. There are also negative equiva-
lents, equality checks, and other combinations that make things simple for you,
the busy developer.
A simple unit test example
Listing 7.1 shows an example test case so you can see these methods used in con-
text. It's designed to test a simple encryption class with two methods,
encrypt()
and
decrypt()
. Although it isn't an exhaustive or complicated test case, it illus-
trates the intent of the unit-testing framework.
Listing 7.1
An example of a simple unit test
import junit.framework.*;
public class CryptTest extends TestCase {
public void testEncrypt() {
String plainText = "convoy sails for England tonight";
String crypted = CryptUtil.encryptString(plainText);
assertFalse("Encrypted value should not be equal to the"+
" original", crypted.equals(plainText));
}
public void testDecrypt() {
String plainText = "my password is elephant";
String crypted = CryptUtil.encryptString(plainText);
String decrypt = CryptUtil.decryptString(crypted);
assertEquals("Decrypted value should be equal to the"+
" original", plainText, decrypt);
}
}