TestNg's @BeforeTest on base class only happening once per fixture

前端 未结 4 517
名媛妹妹
名媛妹妹 2020-12-09 08:06

I\'m trying to use @BeforeTest to get code to ... run once before every test.

This is my code:

public class TestBase {
    @BeforeTest
    public voi         


        
相关标签:
4条回答
  • 2020-12-09 08:30

    According to documentation, a method annotated with @BeforeTest is run before any @Test method belonging to the classes inside the tag is run.

    From my experience:

    • Each @BeforeTest method is run only once
    • If you have several @BeforeTest methods, the order of their execution depends on the order of the class containing those @BeforeTest method.

    You could test this by setting up a simple example.

    0 讨论(0)
  • 2020-12-09 08:34

    "BeforeTest" is only printed once, not twice. What am I doing wrong?

    ***Sorry. I haven't noticed that you is written @BeforeTest , but in your example @BeforeTest almost equals @BeforeClass , and better to use @BeforeClass , when you haven't anymore test classes.

    @BeforeClass" should be declared in same class that your tests methods, not differently!

    //Example
    
    package test;
    import org.testng.annotations.BeforeClass;
    import org.testng.annotations.BeforeMethod;
    import org.testng.annotations.Test;
    
    public class Tests {
    private String bClass;
    private String bMethod1;
    private String bMethod2;
    
    @BeforeClass
    public void beforeClass() {
        bClass = "BeforeClass was executed once for this class";
    }
    
    @BeforeMethod
    public void beforeMetodTest1() {
        bMethod1 = "It's before method for test1";
    }
    
    @Test
    public void test1() {
        System.out.println(bClass);
        System.out.println(bMethod1);
    }
    
    @BeforeMethod
    public void beforeMethodTest2() {
        bMethod2 = "It's before method for test2";
    }
    
    @Test
    public void test2() {
        System.out.println(bClass);
        System.out.println(bMethod2);
    }
    }
    

    @BeforeClass will executed once, before your all tests methods in this class. @BeforeMethod will executed before test method, before which it is written.

    @BeforeClass may be only one in test class, in difference @BeforeMethod!(If it is some @BeforeClass, they are carried out by turns, but it not a correct composition of the test)

    P.S. Sorry for my English :)

    0 讨论(0)
  • 2020-12-09 08:51

    If you use @beforeTest, that method will be run once in the beginning of every <test> (we specify in the test suit xml file) if that test contains that class

    All the @befortests within all the classes within a <test> will be executed at the beggining of that test

    0 讨论(0)
  • 2020-12-09 08:53

    Use @BeforeMethod, not @BeforeTest.

    The meaning of @BeforeTest is explained in the documentation.

    0 讨论(0)
提交回复
热议问题