Over a million developers have joined DZone.

JUnit: Convenient Use Of TestSuite Based On Parameterized TestCases

DZone's Guide to

JUnit: Convenient Use Of TestSuite Based On Parameterized TestCases

· ·
Free Resource
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:


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

- 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 

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


Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}