【问题标题】:How to execute a piece of code once before all test classes start?如何在所有测试类开始之前执行一段代码?
【发布时间】:2019-10-23 18:28:04
【问题描述】:

如何在所有类的所有测试开始之前执行一次方法?

我有一个程序需要在任何测试开始之前设置系统属性。有什么办法吗?

注意:@BeforeClass@Before 仅用于同一个测试类。就我而言,我正在寻找一种在所有测试类开始之前执行方法的方法。

【问题讨论】:

标签: java spring junit4


【解决方案1】:

要为您的测试用例设置先决条件,您可以使用类似这样的东西 -

@Before
public void setUp(){
    // Set up you preconditions here
    // This piece of code will be executed before any of the test case execute 
}

【讨论】:

    【解决方案2】:

    如果您需要在所有测试开始之前运行该方法,您应该使用注解@BeforeClass,或者如果您需要在每次执行该类的测试方法时执行相同的方法,您必须使用@Before

    f.e

    @Before
    public void executedBeforeEach() {
       //this method will execute before every single test
    }
    
    @Test
    public void EmptyCollection() {
      assertTrue(testList.isEmpty());     
    }
    

    【讨论】:

    • 供您参考,在您的回答中,@BeforeClass 被称为 annotation 而不是 tag i>.
    【解决方案3】:

    您可以使用测试套件。

    测试套件

    @RunWith(Suite.class)
    @Suite.SuiteClasses({ TestClass.class, Test2Class.class, })
    public class TestSuite {
    
        @BeforeClass
        public static void setup() {
    
            // the setup
        }
    }
    

    还有,测试类

    public class Test2Class {
    
        @Test
        public void test2() {
    
            // some test
        }
    }
    
    public class TestClass {
    
        @Test
        public void test() {
    
            // some test
        }
    }
    

    或者,您可以拥有一个处理设置的基类

    public class TestBase {
    
        @BeforeClass
        public static void setup() {
    
            // setup
        }
    }
    

    然后,测试类可以扩展基类

    public class TestClass extends TestBase {
    
        @Test
        public void test() {
    
            // some test
        }
    }
    
    public class Test2Class extends TestBase {
    
        @Test
        public void test() {
    
            // some test
        }
    }
    

    但是,这将在每次执行时为其所有子类调用TestBase 中的setup 方法。

    【讨论】:

      猜你喜欢
      • 2019-06-07
      • 1970-01-01
      • 1970-01-01
      • 2013-09-08
      • 1970-01-01
      • 1970-01-01
      • 2013-01-24
      • 2018-06-15
      • 2017-09-03
      相关资源
      最近更新 更多