如何使用多个参数化数据源

时间:2018-09-19 18:43:03

标签: java junit parameterized data-driven-tests

在Junit中使用Parameterized

我想使用来自单独类的两个String [](userId和account)。我知道这对于TestData.users String []会很好用,但是我不确定如何让它也返回TestData.accounts String []并配对数据。

目标是将每个用户ID和帐户配对到每个测试中。

例如:test1使用user1和acct1执行测试,test2使用user2和acct2执行测试,依此类推。

@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));
}

TestData.java

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

我缺少明显的东西吗?预先感谢您的指导!

1 个答案:

答案 0 :(得分:1)

您可以执行以下操作:

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

@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]});
    }
}

有关更多信息,请访问: https://www.tutorialspoint.com/junit/junit_parameterized_test.htm