TestNG: Identifying which tests methods are next

2019-05-28 23:57发布

问题:

My goal is to clear() my javax.persistence.EntityManager after each test method.

Here's an example of a test class:

public class Example
{
    @Test(dataProvider = "sampleDataProvider")
    public void testA(String parameter)
    {
        System.out.println(parameter);
    }

    @Test(dataProvider = "sampleDataProvider")
    public void testB(String parameter)
    {
        System.out.println(parameter);
    }
}

The entityManager is used in the dataProvider "sampleDataProvider" by querying the DB for test data which is then compiled in this format: new Object[2][1]. Keep in mind that the querying and compiling of data is all done before a test method (annotated with @DataProvider) is actually run and that we're actually querying for entities and not just Strings.

The above test class would run like so:

testA("some queried entity 1")
testA("some queried entity 2")
testB("some queried entity 1")
testB("some queried entity 2")

My initial solution was to use the @AfterTest annotation to clear the entityManager. However it would detach "some queried entity 2" from the entityManager before the second-runs (or second test instances) of testA and testB which causes problems on read/write operations to the members of "some queried entity 2".

My goal is to clear the entityManager after a test method, and not necessarily after every instance of a test method.

Does TestNG make it possible to know which test is run next? That way I could easily clear the entityManager if the next test is a new one.

Any other recommendations?

回答1:

I don't know about any easy way to get next test method. BTW, you can achieve the same result using @AfterGroups annotation:

@Test(groups = {"groupA"})
public void testA(...) { ... }

@Test(groups = {"groupB"})
public void testB(...) { ... }

@AfterGroups(groups = {"groupA"})
public void afterGroupA() {
    // clear entity manager here
}

Note, that order of tests starting is not guaranteed by TestNG, until you specify it explicitly with dependsOnMethods or dependsOnGroups parameters of @Test annotation, or "preserve-order" attribute of tag in testng.xml file.

UPDATE

As an alternative you can use your own TestListiner. You can implement onTestStart() method, which will do clearing, if it is necessary. AFAIU, invoked test method is available in partially filled ITestResult. BTW, be careful - this may lead to problems caused by implicit test logics (clearing will not be visible from test code).