What is the difference between BeforeTest and Befo

2019-02-22 05:28发布

问题:

Both annotations runs before the @test in testNG then what is the difference between two of them.

回答1:

@BeforeTest : It will call Only once, before Test method.

@BeforeMethod It will call Every time before Test Method.



回答2:

check below code and output

import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class Test_BeforeTestAndBeforeMethod {

    @BeforeTest
    public void beforeTest()
    {
        System.out.println("beforeTest");
    }

    @BeforeMethod
    public void beforeMethod()
    {
        System.out.println("\nbeforeMethod");
    }


    @Test
    public void firstTest()
    {
        System.out.println("firstTest");
    }

    @Test
    public void secondTest()
    {
        System.out.println("secondTest");
    }

    @Test
    public void thirdTest()
    {
        System.out.println("thirdTest");
    }
}

output:

beforeTest

beforeMethod
firstTest

beforeMethod
secondTest

beforeMethod
thirdTest


回答3:

@BeforeTest : It will be called Only one time befor any test methods, no matter how many method annotaed with @Test, it will be called only one time

@BeforeMethod It will be called befor every methode annotated with @Test, if you have 10 @Test methods it will be called 10 times



回答4:

In TestNG

@BeforeMethod - BeforeMethod executes before each and every test method. All methods which uses @Test annotation. @BeforeMethod works on test defined in Java classes.

@BeforeTest - BeforeTest executes only before the tag given in testng.xml file. @BeforeTest works on test defined in testng.xml

Reference:- https://examples.javacodegeeks.com/enterprise-java/testng/testng-beforetest-example/ and http://howtesting.blogspot.com/2012/12/difference-between-beforetest-and.html



回答5:

@BeforeTest is executed before any beans got injected if running an integration test. In constrast to @BeforeMethod which is executed after beans injection. Not sure why this was designed like this.



回答6:

@BeforeTest will execute only one time before any test methods. Methods will run before executing any @Test annotated test method that is part of the <test> tag in testNG.xml file. @BeforeMethod will execute before every method annotated with @Test.



回答7:

@BeforeTest To execute a set-up method before any of the test methods included in the < test > tag in the testng.xml file. @BeforeMethod To execute a set-up method before any of the test methods annotated as @Test.



标签: testng