RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


JUnit and Its Extensions Make Unit Testing Your Java Code Much Easier : Page 4

In an age when any professional Java developer has to know how to properly unit test the code he or she writes, JUnit and its extensions can make writing your tests easier and more effective.

Tracking the Causes of Test Failures with JUnit Assertions
JUnit assertions all have the ability to take a string as a name that will be output with a test's failure details. This makes tracking down the cause of a failure easier when using check methods. If to the parameter list for the dialog-checking method you used, you'd get the following method:

private void checkDialogAppears(String testName, String expected, 
String usernameText, String passwordText) throws Exception { setText(username, usernameText); setText(password, passwordText); helper.enterClickAndLeave(new MouseEventData(this, ok)); List showingDialogs = helper.getShowingDialogs(main); assertEquals(testName, 1, showingDialogs.size()); JDialog dialog = (JDialog) showingDialogs.get(0); assertEquals(testName, expected, dialog.getTitle()); helper.disposeWindow(dialog, this); }
The four routines that use this method are rather similar, except for the strings they use. So you could bring them together into an array of test data with a single test method, like this:

public void testOkayBehavior() throws Exception {
  String[][] testData = {
    {"Blank username", "Logon Error: username", "", "admin"},
    {"Blank password", "Logon Error: password", "admin", ""},
    {"Blank username & password", "Logon Error: username/password", "", ""},
    {"Logging on", "Logging on", "admin", "admin"} };

  for (int i = 0; i < testData.length; i++)
    checkDialogAppears(testData[i][0], testData[i][1], testData[i][2], 
testData[i][3]); }
If you need another test of this type, you need only add another line to the test data array. This is a common pattern in testing, and you can easily generalize it to other general input forms. You write a method that fills the form and tests that the next form is the one you expect, and then you fill the form from an array containing test data.

New Tools for Your Bag of Tricks
In an age when any professional Java developer has to know how to properly unit test the code he or she writes, JUnit, JUnit-Addons, and jfcUnit should be at the top of your bag of tricks. Use these tools to make writing your tests easier and more effective. Rarely will you need to dig deeper into your bag for less common tools.

Bryan Dollery is an experienced Java trainer and software engineer living in New Zealand. He recently presented papers at three major international software development conferences (in NZ and Australia). Reach him by e-mail at Bryan.Dollery@ChaosEngineers.co.nz.
Email AuthorEmail Author
Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date