bjones01001101
bjones01001101

Reputation: 1181

How to use multiple sources of parameterized data

Using Parameterized in Junit.

I would like to use two String[] (userId and account) from a separate class. I know this will work fine for the TestData.users String[], but I am unsure how to have it also return TestData.accounts String[] and pair the data.

The goal is to pair off each userId and account into each test.

For example: test1 uses user1 and acct1 to execute the test, test2 uses user2 and acct2 to execute the test, and so forth.

@RunWith(Parameterized.class)
public class TestUpdateUserAccounts extends Base {

private String userId;
private String account;

public TestUpdateUserAccounts(String userId, String account) {
    this.userId = userId;
    this.account = account;
}

@Parameters(name = "{0}")
public static Collection userPlusAccount() {
    return Arrays.asList(TestData.users);
    // NEED HELP HERE - HOW TO PAIR EACH TestData.accounts WITH EACH USER
}

@Test
public void checkUserAccount() {
    //code here that will execute some steps
    assertTrue(user.connectedToAccount(account));
}

In the TestData.java

public static String[] users = { "user1", "user2", "user3", "user4", "user5" };
public static String[] accounts = { "acct1", "acct2", "acct3", "acct4", "acct5" };

Am I missing something quite obvious? Thank you in advance for any guidance!

Upvotes: 1

Views: 98

Answers (1)

D. Mayen
D. Mayen

Reputation: 464

You can do something like this:

@Parameters
 public static Collection userPlusAccount() {
  return Arrays.asList(new Object[][] {
     { "user1", "acct1" },
     { "user2", "acct2" },
     { "user3", "acct3" },
     { "user4", "acct4" },
     { "user5", "acct5" }
  });
 }

or

@Parameterized.Parameters
public static Collection userPlusAccount() {
    List<Object[]> list = new ArrayList<>();
    for(int i = 0; i<TestData.getSize(); i++) {
        list.add(new Object[]{TestData.users[i], TestData.accounts[i]});
    }
}

For more information visit: https://www.tutorialspoint.com/junit/junit_parameterized_test.htm

Upvotes: 1

Related Questions