【问题标题】:Call @Before and @After methods for each test in a suit为西装中的每个测试调用 @Before 和 @After 方法
【发布时间】:2014-10-13 15:49:06
【问题描述】:

我的所有测试都有班级跑者:

import org.junit.*;
import org.junit.rules.TestName;
import org.junit.rules.TestRule;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
import org.junit.runner.Result;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;

import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.List;

@RunWith(Suite.class)
@Suite.SuiteClasses({

   Test1.class,
   Test2.class,
   Test3.class,
   Test4.class,
   Test5.class
})

public class AllTestRunner {
   ...
@Before
public void method1() {}

@After 
public void method2() {}

我需要为SuiteClasses 的每个班级中的每个@Test 运行method1()method2()。 但它不起作用,可能是我做某事。错了吗?

感谢您的帮助,对不起我的英语。

【问题讨论】:

标签: java testing junit automated-tests


【解决方案1】:

首先,创建一个抽象类BasicTest:

//
    @Rule
    public TestWatcher watcher = new TestWatcher() {

        @Override
        protected void starting(Description description) {
        }

        @Override
        protected void succeeded(Description description) {
        }

        @Override
        protected void failed(Throwable e, Description description) {
        }

        @Override
        protected void skipped(AssumptionViolatedException e, Description description) {
        }

        @Override
        public void finished(Description description) {
        }
    };
//...

对于每个测试类:

public class Test extends BasicTest { }

因此,对于每个 @Test 都会从 TestWatcher 调用方法。

【讨论】:

    【解决方案2】:

    这是因为 @Before@After@BeforeClass@AfterClass 是类相关的。换句话说,它们只涉及定义它们的类。

    抱歉,无法使用这些注释来实现您尝试实现的目标。您必须在每个 SuiteClasses 中复制您的方法

    【讨论】:

      【解决方案3】:

      您也可以使用规则。这种方法的优点是您不需要继承某个类。

      在一个类中,您实现了一个规则,该规则指定在测试用例执行之前和之后要执行的行为。

      public class MyRule implements MethodRule {
        public Statement apply(final Statement statement, final FrameworkMethod frameworkMethod, final Object o) {
          return new Statement() {
              @Override
              public void evaluate() throws Throwable {
                  try {
                      before();
                      statement.evaluate();
                  } finally {
                      after();
                  }
              }
          };
        }
      
        protected void before() {
          System.out.println("before");
        }
      
        public void after() {
          System.out.println("after");
        }
      }
      

      然后您可以在应该使用它的每个测试类中实例化该规则。不需要继承。

      public class TestClass {
      
        @Rule
        public MyRule myRule = new MyRule();
      
        @Test
        public void test() {
        }
      }
      

      【讨论】:

        猜你喜欢
        • 2012-01-12
        • 2013-01-21
        • 1970-01-01
        • 1970-01-01
        • 2023-03-04
        • 1970-01-01
        • 2012-05-21
        • 2016-01-01
        • 2010-12-14
        相关资源
        最近更新 更多