DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

JUnit: Convenient Use Of TestSuite Based On Parameterized TestCases

09.19.2005
| 7693 views |
  • submit to reddit
        Here's a frequently (at least for me) occurring problem: let's say
you have a TestCase where each testXXX() method really does mostly 
the same thing, parameterized by some instance variables. For instance,
I have a file consisting of good data for each parameter, such as:

goodAAA=foo
goodBBB=bar
goodCCC=baz
...

You don't want to create tens or hundreds of methods (testAAA(), 
testBBB(), etc.) by copying and pasting. So you create a TestCase that 
has:

- An field called, say, key

- A single testKey() method that, based on the 
key, gets the good data, gets the test data and compares them.

- static suite() method that, in a loop, creates instances of your 
TestCase and sets their keys appropriately.

This is all well and good. But when you run it, a failure will always 
show up in testKey() method in JUnit's UI. (Sure, you can add a message
that shows the key for which it failed, but it does not give
you an at-a-glance feedback.)

So for convenience, you override getName() to return key. Now
it's very easy to tell, by merely glancing at that JUnit bar, what 
failed. 

But if you run it within IDE, say, Eclipse, you want to click on the 
failed test so that Failure Trace appears, where you can click on any 
Stack Trace Element and get to the exact line of failure in your code. 
But because the failed test's name is based on the key field, it does 
not correspond to a real testXXX() method in your TestCase. So your
IDE can't take you to the code that failed.

Here's how to override getName() to get the best of both worlds:

public String getName() {
    StackTraceElement[] st = new Throwable().getStackTrace();
    if (st.length < 4 || !st[3].getMethodName().equals("endTest")) {
        return key; 	  // Meaningful name to appear in the bar
    } else {
        return "testKey"; // Real method name to appear in Failure Trace
    }
}