score:0

will this work ?

public class beforestuff {
@beforemethod()
}

public class test1 {
    @test
    @test
}

public class test2 {
    @test
}

public class test3 {
    @test
    }
}

score:1

if your goal is to remove duplication of tests, how about creating more invidualized tests and running them multiple times by specifying so in a testng.xml file?

for example, you could do:

<?xml version="1.0" encoding="utf-8"?>

<suite name="test suite 1">
    <test name="test set 1">
        <classes>
            <class name="test.mytest.test1" />
            <class name="test.mytest.test2" />
        </classes>
    </test>
    <test name="test set 2">
        <classes>
            <class name="test.mytest.test1" />
            <class name="test.mytest.test3" />
        </classes>
    </test>
</suite>

with your classes set up as:

public class test1 {

    @beforemethod
    public void before(){
        system.out.println("==before method==");
    }

    @test
    public void testlogin(){
        system.out.println("test login");
    }

    @test
    public void testsubmit(){
        system.out.println("test submit");
    }

}

public class test2 {

    @test
    public void testaccept(){
        system.out.println("test accept");
    }

}

public class test3 {

    @test
    public void testreject(){
        system.out.println("test reject");
    }

}

when run(i used maven in my example), will produce:

running testsuite
==before method==
test login
==before method==
test submit
test accept
==before method==
test login
==before method==
test submit
test reject
tests run: 6, failures: 0, errors: 0, skipped: 0, time elapsed: 0.253 sec - in testsuite

for this example i organized them by class, but you could organize by group, method, etc.

edit based on your comment i added an example of using @beforemethod and the output produced.

if you are looking to specifically reuse your @beforemethod, i suppose you could always just throw it into a base class and have your test cases extend it:

public class testbase {

    @beforemethod
    public void before(){
        system.out.println("==before method==");
    }
}

public class test1 extends testbase{

    @test
    public void testlogin(){
        system.out.println("test login");
    }

    @test
    public void testsubmit(){
        system.out.println("test submit");
    }

}

i've never needed to do something like that, so i can't speak to it in terms of best practices, but it would work.


Related Query

More Query from same tag