Vladimir Bogodukhov
Vladimir Bogodukhov

Reputation: 31

JUnit5 - is there any reliable way to get class of an executed test

I am writing a test execution listener. A little extension for Junit5 framework. There is a necessity to know what class is used when running a particular test having TestIdentifier and TestPlan.

((MethodSource) id.getSource().get()).getClassName(); 

Gives only the class, where a test is declared. But, that does not mean that it is run from declared class.

For instance a test can be run from a subclass.

Parsing results for TestIdentifier#getUniqueId() Can differ from case to case (single test for junit4, single test for junit5, dynamic test for junit5 , parametrized test for junit4, etc)

At this moment I did not find any possibility to do that.

Is there any reliable way to get class of an executed test ?

Upvotes: 2

Views: 1961

Answers (2)

Vladimir Bogodukhov
Vladimir Bogodukhov

Reputation: 31

I found temporary solution for described situation. The idea is to go through all parents and find first that contains ClassSources, then use that ClassSource.

private static String findTestMethodClassName(TestPlan testPlan, TestIdentifier identifier) {
    identifier.getSource().orElseThrow(IllegalStateException::new);
    identifier.getSource().ifPresent(source -> {
        if (!(source instanceof MethodSource)) {
            throw new IllegalStateException("identifier must contain MethodSource");
        }
    });


    TestIdentifier current = identifier;
    while (current != null) {
        if (current.getSource().isPresent() && current.getSource().get() instanceof ClassSource) {
            return ((ClassSource) current.getSource().get()).getClassName();
        }
        current = testPlan.getParent(current).orElse(null);
    }
    throw new IllegalStateException("Class name not found");
}

Although that solution covers my needs it makes no guaranty that framework behaviour is not changed in future and cannot be considered reliable at this moment.

The issue is posted to https://github.com/junit-team/junit5/issues/737

Upvotes: 1

Marc Philipp
Marc Philipp

Reputation: 1908

Save a reference to TestPlan in testPlanExecutionStarted and inspect the TestSource of the TestIdentifier's parent using testPlan.getParent(testIdentifier). If it's a ClassSource, you can access the Class via classSource.getJavaClass().

Upvotes: 3

Related Questions