我正在尝试将现有项目从3.0.2升级到5.5.0。该项目在Cucumber.java运行器类中具有getDescription()的自定义实现,并且必须维护该功能,因为它在其他项目中具有依赖项。 JUnit版本为4.12。
在3.0.2中,Cucumber.java运行器类在cucumber.api.junit.Cucumber中定义为
public class Cucumber extends ParentRunner<FeatureRunner>
这使得自定义运行器非常简单:
public class DescriptiveCucumberRunner extends Cucumber
{
public DescriptiveCucumberRunner(Class<?> testClass) throws InitializationError, IOException
{
super(testClass);
}
@Override
public Description getDescription()
{
String text = "Cucumber tests running on " + new Date();
Description originalDescription = super.getDescription();
Description newDescription = originalDescription.childlessCopy();
newDescription.addChild(Description.createSuiteDescription(text));
for(Description childDescription : originalDescription.getChildren())
{
newDescription.getChildren().get(0).addChild(childDescription);
}
return newDescription;
}
}
在5.0.0中,将Cucumber.java运行器类移至io.cucumber.junit.Cucumber,并将定义更改为]
public final class Cucumber extends ParentRunner<ParentRunner<?>>
所以我不再能够扩展。
我尝试扩展org.junit.runners.ParentRunner
public class DescriptiveCucumberRunner extends ParentRunner<Cucumber>
并且与委托进行聚合,但是由于Cucumber.java的方法受到保护,所以我基本上必须复制整个类以保留当前功能,而这根本不是一个解决方案。我可以使用反射来调用Cucumber.java中定义的方法,但这也不是很干净。
有人知道如何做到这一点而无需更改其他项目吗?也许有一种我不了解的使用黄瓜的预期方法?希望我只是在这个问题上缺少一个明显的解决方案,但是到目前为止,我还是有一个空白。
通常最好使用组合而不是继承。因此,与其扩展现有的Cucumber
运行器类,您不妨考虑实现自己的运行器类,该类具有Cucumber
运行器的实例作为其子代之一。
package com.example;
import io.cucumber.junit.Cucumber;
import org.junit.runner.Description;
import org.junit.runner.notification.RunNotifier;
import org.junit.runners.ParentRunner;
import org.junit.runners.model.InitializationError;
import java.util.ArrayList;
import java.util.List;
public class MyCustomRunner extends ParentRunner<Cucumber> {
private final List<Cucumber> children = new ArrayList<>(1);
protected MyCustomRunner(Class<?> testClass) throws InitializationError {
super(testClass);
this.children.add(new Cucumber(testClass));
}
@Override
public Description getDescription() {
return // your custom description;
}
@Override
protected List<Cucumber> getChildren() {
return children;
}
@Override
protected Description describeChild(Cucumber child) {
return child.getDescription();
}
@Override
protected void runChild(Cucumber cucumber, RunNotifier runNotifier) {
cucumber.run(runNotifier);
}
}