JUnit 4 can’t tell the test its name!
TestCase.getName() was useful from time to time. I recently used it on a project where the name of the test was used as the “client application” name in the database connection properties. This was good for tracking what tests were doing in the database when they made use of stored procedures (by using SQLSleuth for example).
JUnit 4 does not have any out-of-the-box mechanism for a test case to get it’s own name (including during setup and teardown).
JUnit 4 has some interesting architectural changes under-the-covers (some of which we’ll touch on shortly), but the main change to the outside world was the use of annotations to drive the testing framework.
Previously, we used framework-imposed conventions — like test cases must be public void methods whose name starts with “test” in a class that extends a subclass of TestCase, and de facto conventions — like tests are in the “test” source tree and, if a unit test, have the name of the class they’re testing with the suffix (or prefix) “Test”.
The TestCase base class came with some nice properties, like getting the name of the current test case.
<siderant>
Is the new API so much more fabulous than the old? As Jason Yip asked me, “Does it make you write your tests any better?”. For my piece of the apple pie, I don’t think so.
<\siderant>
So, as JUnit 4 does not use inheritence from TestCase, you lose the properties the base class provided, and that includes getName(). So how does my test case know it’s name?
Before you reach for your Throwable, it’s no good just looking at the stack because @Before and @After methods may want to know the test case name too, and their method name isn’t it.
It turns out that this little gem was not included in the gift-wrapped functionality of JUnit 4. I had a little hunt around and found a posting by Gabriel Cooper that held the key. I set about testing it and making sure the global mutable state the technique requires was at least thread-safe.
Here’s the result. Hopefully something of it’s like appears in the default runner sometime soon (and it could do it in it’s run() method without messing around with listeners).
Visit the ThoughtWorks Sydney GeekNight code repository to have a look at the full Eclipse project with multi-threading tests (also has some nice use of Futures to assist in testing for thread-safety).