我找到了描述情况的临时解决方案。这个想法是遍历所有父母并首先找到包含 ClassSources,然后使用该 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");
}
尽管该解决方案满足了我的需求,但它不能保证框架行为将来不会改变,并且目前不能被认为是可靠的。
该问题已发布到https://github.com/junit-team/junit5/issues/737