【问题标题】:How to perform @After for a specific JUnit test case?如何为特定的 JUnit 测试用例执行 @After?
【发布时间】:2017-11-08 08:16:19
【问题描述】:

我正在使用 Espresso 构建 UI 测试。对于某些测试用例,我想调用一个特定的后续步骤来重置状态,以防脚本失败。

有没有办法为单个 JUnit 测试用例 (@Test) 执行 @After 步骤? 我能想到的唯一解决方案是制作一个单独的测试类。但我希望将测试用例分组到同一个测试类中。

【问题讨论】:

    标签: android unit-testing junit automated-tests android-espresso


    【解决方案1】:

    听起来确实有点奇怪;)但是...

    • 您可以将 try/finally 添加到您想要此 after 行为的单个测试中。例如:

      @Test
      public void testA() {
          try {
              // the body of testA
          } finally {
              // apply the 'after' behaviour for testA 
          }
      }
      
    • 或者,如果您真的想使用 JUnit 的 @After,那么您可以使用 TestName Rule(自 JUnit 4.7 起),如下所示:

      @Rule
      public TestName testName = new TestName();
      
      @After
      public void conditionalAfter() {
          if ("testB".equals(testName.getMethodName())) {
              System.out.println("apply the 'after' behaviour for testB");
          }
      }
      
      @Test
      public void testA() {
      
      }
      
      @Test
      public void testB() {
      
      }
      

    【讨论】:

    • 因为提到了 TestName 规则而被赞成,因为我使用了 contiperf,它对我帮助很大
    猜你喜欢
    • 2018-04-23
    • 2013-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-28
    • 1970-01-01
    • 2019-01-29
    • 1970-01-01
    相关资源
    最近更新 更多