Junit-多个@Before与一个@Before拆分为方法 [英] Junit - Multiple @Before vs. one @Before split up into methods

查看:943
本文介绍了Junit-多个@Before与一个@Before拆分为方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在单元测试中,我需要执行一个非常复杂的设置(这可能是代码的味道,但这不是此问题的实质:-).我感兴趣的是,最好让多个@Before方法执行设置,或者只让一个调用帮助方法执行初始化的方法.

In a unit test, I need to perform a quite complex setup (this may be a code smell but this is not what this question is about :-)). What I'm interested in is if it is better to have multiple @Before methods performing the setup or just one, which calls helper methods to perform the initialization.

例如

@Before
public void setUpClientStub() {

}

@Before
public void setUpObjectUnderTest() {

}

vs.

@Before
public void setUp() {
    setUpClientStub();
    setUpObjectUnderTest();
}

推荐答案

如其他响应中所述,不能保证JUnit查找方法的顺序,因此不能保证@Before方法的执行顺序. @Rule也是一样,它同样缺乏保证.如果这将始终是相同的代码,那么将其分为两个方法没有任何意义.

As has been said in other responses, the order in which JUnit finds methods is not guaranteed, so the execution order of @Before methods can't be guaranteed. The same is true of @Rule, it suffers from the same lack of guarantee. If this will always be the same code, then there isn't any point in splitting into two methods.

如果您确实有两种方法,更重要的是,如果您希望在多个地方使用它们,则可以使用

If you do have two methods, and more importantly, if you wish to use them from multiple places, then you can combine rules using a RuleChain, which was introduced in 4.10. This allows the specific ordering of rules, such as:

public static class UseRuleChain {
  @Rule
  public TestRule chain= RuleChain
               .outerRule(new LoggingRule("outer rule"))
               .around(new LoggingRule("middle rule"))
               .around(new LoggingRule("inner rule"));

  @Test
  public void example() {
      assertTrue(true);
  }
}

这将产生:

starting outer rule
starting middle rule
starting inner rule
finished inner rule
finished middle rule
finished outer rule

因此您可以升级到4.10或只是偷听课程.

So you can either upgrade to 4.10 or just steal the class.

在您的情况下,您可以定义两个规则,一个用于客户端设置,一个用于对象,然后将它们组合为RuleChain.使用 ExternalResource .

In your case, you could define two rules, one for client setup and one for object, and combine them in a RuleChain. Using ExternalResource.

public static class UsesExternalResource {
  private TestRule clientRule = new ExternalResource() {
      @Override
      protected void before() throws Throwable {
        setupClientCode();
      };

      @Override
      protected void after() {
        tearDownClientCode()
    };
  };

  @Rule public TestRule chain = RuleChain
                   .outerRule(clientRule)
                   .around(objectRule);
}

因此,您将具有以下执行顺序:

So you'll have the following execution order:

clientRule.before()
objectRule.before()
the test
objectRule.after()
clientRule.after()

这篇关于Junit-多个@Before与一个@Before拆分为方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆