Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TestNG. Need to run specific method before all tests and specifiic test after all tests

Tags:

maven

testng

Used Selenium + TestNG + Maven.

I want to automate testing vulnerabilities using OWASP ZAP. For this I need to start ZAProxyScanner before all tests - execute method before all tests.

public void initZap(){
        zapScanner = new ZAProxyScanner(ZAP_PROXYHOST,ZAP_PROXYPORT,ZAP_APIKEY);
        zapScanner.clear(); //Start a new session
        zapSpider = (Spider)zapScanner;
}

and when all functional tests were executed - run test for searching vulnerabilities

@Test
public void scanning() throws ClientApiException{
    spiderWithZap();
    setAlertAndAttackStrength();
    zapScanner.setEnablePassiveScan(true);
    scanWithZap();
}

Method and test located in one class, e.g. public class TestSecurity

Here is sample of my testng.xml with packages containing functional tests

<suite name="Chrome" thread-count="1" parallel="tests" configfailurepolicy="continue">
<test name="chrome">
    <parameter name="browser" value="chrome"/>
    <packages>
        <package name="tests.suiteLogIn"></package>
        <package name="tests.suiteSettings"></package>
        <package name="tests.suiteSearch"></package>
    </packages>    
</test>

UPD. post modified code with AfterTest in it. I use only Before/AfterMethod annotations

    @BeforeMethod(alwaysRun=true)
@Parameters({"browser", "environment"})
public void setUp(@Optional ("firefox") String browser, @Optional ("local") String environment, Method method) throws IOException {
    System.out.println("Test name: " + method.getName());  
    WebDriver driver = getMyDriver(browser, environment);
    System.setProperty(ESCAPE_PROPERTY, "false");
}

@AfterMethod(alwaysRun=true)
@Parameters("browser")
public void tearDown(@Optional ("firefox") String browser){
    DriverMaster.stopDriver();
}

@BeforeSuite
@Parameters("browser")
public void startZap(@Optional ("firefox") String browser){
    if(browser.equals("firefox")){
        sec.initZap();
    }
}

@AfterSuite
@Parameters("browser")
public void scanZap(@Optional ("firefox") String browser) throws ClientApiException{
    if(browser.equals("firefox")){
        LoginPage lp = new LoginPage(getDriverInstance()).load();
        lp.login("name", "pass");
        sec.scanning();
    }
}
like image 487
user3535807 Avatar asked Dec 26 '22 03:12

user3535807


1 Answers

You basically have two options:

  1. Use @BeforeSuite and @AfterSuite and include that in the files to run or make all your classes extend it

  2. Use ITestListener or ISuiteListener and put the setup and teardown code in their before and after methods.

With listeners, one advantage that I can see is if you want to do conditional teardown (scanning) based on some testresults you can control that too.

like image 68
niharika_neo Avatar answered Apr 26 '23 18:04

niharika_neo