简体   繁体   中英

How to make TestNG @DataProvider which returns several objects returns only one?

I have following @DataProvider :

@DataProvider(name = "CredentialsProvider", parallel = true)
public static Object[][] credentialsProvider() {

    ...

    for (int i = 0; i < login.size(); i++) {
        credentials[i] = new Object[] {login.get(i)[0], password.get(i)[0]};
    }
    return credentials;
}

It used to generate credentials for test which are run in parallel mode:

@Test(dataProvider = "CredentialsProvider")
public void Login (String login, String password)

But sometimes I want to use the same @DataProvider in a test with only single run. I expected that using of invocationCount in @Test method will help with it, but was wrong. Is there any solution to invoke @DataProvider only once regardless on number of objects returned by provider without changing it's sources?

AFAIK you can only deal with this issue on the data provider side.

@DataProvider(name = "CredentialsProvider", parallel = true)
public static Object[][] credentialsProvider(Method method) { ... }

@DataProvider(name = "CredentialsProvider", parallel = true)
public static Object[][] credentialsProvider(ITestContext context) { ... }

In both cases you can get information from the context of the test cases which are using the data provider. In first case, for example method.getName(); gives you the name of the @Test method. In second case, context.getName(); gives you the name of the test case ( <test name="TestName"> ) inside the test suite.

And I meant something like this:

for (int i = 0; i < login.size(); i++) {
    credentials[i] = new Object[] {login.get(i)[0], password.get(i)[0]};
    if(i > MAX_COUNT && "EXPECTED_TEST_NAME".equals(context.getName())) { break; }
}

Make your DataProvider accept an argument of type Method, and write your own custom annotation to handle this. Something like:

@DataProvider(name = "CredentialsProvider", parallel = true)
public static Object[][] credentialsProvider(Method method) {
    //code to extract custom annotation value
    ....
}

@Test(dataProvider = "CredentialsProvider")
@RunCount(1)
public void test(String login, String password) {
....
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM