代码之家  ›  专栏  ›  技术社区  ›  Sagar Varpe

setup()和setupbeforeclass()之间的差异

  •  153
  • Sagar Varpe  · 技术社区  · 14 年前

    使用JUnit进行单元测试时,有两种类似的方法, setUp() setUpBeforeClass() . 这些方法有什么区别?还有,两者的区别是什么 tearDown() tearDownAfterClass() ?

    签名如下:

    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
    }
    
    @AfterClass
    public static void tearDownAfterClass() throws Exception {
    }
    
    @Before
    public void setUp() throws Exception {
    }
    
    @After
    public void tearDown() throws Exception {
    }
    
    4 回复  |  直到 12 年前
        1
  •  193
  •   Andrzej Doyle    14 年前

    这个 @BeforeClass @AfterClass 在测试运行期间,注释方法将只运行一次——在整个测试开始和结束时,在运行任何其他方法之前。实际上,它们是在构建测试类之前运行的,这就是为什么必须声明它们的原因。 static .

    这个 @Before @After 方法将在每个测试用例之前和之后运行,因此可能在测试运行期间多次运行。

    所以假设您的类中有三个测试,方法调用的顺序是:

    setUpBeforeClass()
    
      (Test class first instance constructed and the following methods called on it)
        setUp()
        test1()
        tearDown()
    
      (Test class second instance constructed and the following methods called on it)
        setUp()
        test2()
        tearDown()
    
      (Test class third instance constructed and the following methods called on it)
        setUp()
        test3()
        tearDown()
    
    tearDownAfterClass()
    
        2
  •  15
  •   Bill the Lizard    13 年前

    把“beforeclass”想象成测试用例的静态初始值设定项-用它初始化静态数据-在测试用例中不会改变的东西。您一定要小心不线程安全的静态资源。

    最后,使用“afterclass”注释方法清除在“beforeclass”注释方法中所做的任何设置(除非它们的自我销毁足够好)。

    “before”&“after”用于单元测试特定的初始化。我通常使用这些方法来初始化/重新初始化依赖项的模拟。显然,这个初始化不是特定于单元测试的,而是通用于所有单元测试的。

        3
  •  7
  •   netbrain    14 年前

    SetupBeforeClass在构造函数之后的任何方法执行之前运行(仅运行一次)

    在每个方法执行之前运行安装程序

    在每个方法执行之后运行TearDown

    TearDownAfterClass在所有其他方法执行之后运行,是最后一个要执行的方法。(只运行一次解构器)

        4
  •  4
  •   Pops Atula    12 年前

    the Javadoc :

    有时,一些测试需要共享计算上昂贵的设置(比如登录到数据库)。虽然这会损害测试的独立性,但有时这是一个必要的优化。注释A public static void 没有arg方法 @BeforeClass 使它在类中的任何测试方法之前运行一次。这个 @ BeforeClass 超类的方法将在当前类的方法之前运行。