是否有像 JUnit @BeforeAll 一样在类构造函数之前开始运行的 TestNG 注释?

问题描述 投票:0回答:1

JUnit @BeforeAll 测试在构造函数和声明的类变量之前执行(它们应该如此)。

TestNG @BeforeClass 在运行之前首先调用类构造函数和类变量。

在调用类构造函数之前是否有开始运行的 TestNG 注释, 就像 JUnit @BeforeAll 一样?

我用 TestNG @BeforeClass 和 JUnit @BeforeAll 进行了测试,它们都给出了不同的响应。

JUnit 示例:

package Junit;

import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import pages.MyClass;

public class TestJunit {

    @BeforeAll
    public static void setUp(){
        System.out.println("1 - @BeforeAll Junit");
    }

    private MyClass str = new MyClass();

    public TestJunit() {
        System.out.println("3 - Junit Class Constructor");
    }

    @Test
    public void test1(){
        System.out.println("4 - Starting Junit Tests");
    }

}

  • TestJunit - Junit 响应:
  1. @BeforeAll Junit
  2. 我的自定义类构造器
  3. Junit 类构造函数
  4. 开始 Junit 测试

TestNG 示例:

package TestNG;

import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import pages.MyClass;

public class TestTestNG {

    @BeforeClass(alwaysRun = true)
    public void setUp(){
        System.out.println("1 - BeforeAll TestNG");
    }

    private MyClass str = new MyClass();

    public TestTestNG() {
        System.out.println("3 - TestNG Class Constructor");
    }

    @Test
    public void test1(){
        System.out.println("4 - Starting TestNG Tests");
    }

}

  • TestTestNG - TestNG 响应:
  1. 我的自定义类构造器
  2. TestNG 类构造器
  3. 所有测试NG之前
  4. 开始 TestNG 测试

我的自定义类:

package pages;

public class MyClass {

    public MyClass() {
        System.out.println("2 - My Custom Class Constructor");
    }
}

我想要一个 TestNG 解决方案(因为 @BeforeClass 不工作),它将给出与 JUnit(@BeforeAll)解决方案相同的响应。

在调用类构造函数之前是否有开始运行的 TestNG 注释, 就像 JUnit @BeforeAll 一样?

java junit annotations automated-tests testng
1个回答
0
投票

是的。您可以使用 @BeforeTest 或顶级 @BeforeSuite 注释用作“BeforeAll”替代。两者都将在测试类构造函数之前运行。 以下是 TestNG 注释执行顺序,因此您明白了。

© www.soinside.com 2019 - 2024. All rights reserved.