0

I'm implementing a custom JUnit Runner and would like to add additional reporting capabilities to it. I'd also like to reuse as much existing JUnit infrastructure as possible, so implementing a RunListener sounded like a good idea. Methods of RunListener either take a Description or a Failure, both with no obvious way to add additional information about the testcases.

Description is effectively final because it has no public constructor, so overriding it is not possible. There is a private uniqueId field that could be misused via reflection but that would be really hacky.

A slightly less hacky variant might be to define annotations for all the information I need and attach implementations of this annotation to the Description. Has anyone done something like this or is there a recommended way how this could be handled?

Here is an example of what I'm currently trying:

public @interface StepMetadata {
    int lineNumber();
    String keyword();
    String title();
}

public class StepMetadataImpl implements StepMetadata {
    private final int lineNumber;
    private final String keyword;
    private final String title;

    // constructor and accessor methods

    @Override
    public Class<? extends Annotation> annotationType() {
        return StepMetadata.class;
    }
}


// inside the Runner
Description.createTestDescription(className, stepTitle, new StepMetadataImpl(...))

// inside the RunListener
StepMetadata step = description.getAnnotation(StepMetadata.class)

Related question, are there any downsides to writing implementations of annotation interfaces?

Jörn Horstmann
  • 33,639
  • 11
  • 75
  • 118
  • [The documentation](http://junit.sourceforge.net/javadoc/org/junit/runner/Description.html#createTestDescription%28java.lang.Class,%20java.lang.String,%20java.lang.annotation.Annotation...%29) certainly suggests annotations are for this purpose: "*annotations - meta-data about the test, for downstream interpreters*". I'm a little unclear about your actual question though - have you tried this and failed? Are you unsure if this is the right approach? – Duncan Jones Oct 15 '14 at 14:16
  • @Duncan: Thanks, I'm unsure if this is the right approach if my underlying tests are not actual java methods and I have to create the annotations myself. I have not come across much code that uses this little-known feature. And to do it correctly seems a little bit more complicated, now that I found this previous answer about `AnnotationLiteral`: http://stackoverflow.com/a/7084532/139595 – Jörn Horstmann Oct 15 '14 at 16:33

0 Answers0