junit外部资源@rule order

igsr9ssn  于 2021-06-03  发布在  Hadoop
关注(0)|答案(3)|浏览(351)

我想在我的测试类中使用多个外部资源,但是在外部资源的排序上有问题。
下面是代码片段:

public class TestPigExternalResource {

     // hadoop external resource, this should start first
     @Rule
     public HadoopSingleNodeCluster cluster = new HadoopSingleNodeCluster();

     // pig external resourcem, this should wait until hadoop external resource starts
     @Rule
     public  PigExternalResource pigExternalResource = new PigExternalResource(); 

     ...  
}

问题是它试图在hadoop启动之前启动pig,因此我无法连接本地hadoop单节点集群。
有没有什么办法来订junit的规则?
谢谢

umuewwlo

umuewwlo1#

你可以使用规则链。

@Rule
public TestRule chain= RuleChain.outerRule(new HadoopSingleNodeCluster())
                           .around(new PigExternalResource());
wvyml7n5

wvyml7n52#

你为什么不把这两个包起来 ExternalResources 你自己的 ExternalResource 这就叫 before 以及 after 从新资源的 before 以及 after 方法。
例子:

public class MyResource extends ExternalResource{
     private final List<ExternalResource> beforeResources;
     private final List<ExternalResource> afterResources;

     public MyResource(List<ExternalResource> beforeResources,
          List<ExternalResource> beforeResources){
     }

      public void before(){
          for (ExternalResource er : beforeResources)
               er.before();
      }

      public void after(){
          for (ExternalResource er : afterResources)
               er.after();
      }
}

public class TestPigExternalResource {

 // hadoop external resource, this should start first
 public HadoopSingleNodeCluster cluster = new HadoopSingleNodeCluster();

 // pig external resourcem, this should wait until hadoop external resource starts
 public  PigExternalResource pigExternalResource = new PigExternalResource(); 

  @Rule
  public MyResource myResource = new MyResource(
          newArrayList(cluster, pigExternalResource),
          newArrayList(cluster, pigExternalResource));
 ...  
}
ars1skjm

ars1skjm3#

中有一个新的order属性 @Rule 以及 @ClassRule 从JUnit4.13-beta-1开始。
看到了吗 @Rule 代码:

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.METHOD})
public @interface Rule {

    int DEFAULT_ORDER = -1;

    /**
     * Specifies the order in which rules are applied. The rules with a higher value are inner.
     *
     * @since 4.13
     */
    int order() default DEFAULT_ORDER;

}

另请参见本请购单:pr-1445。

相关问题