TestNG方法中的可变长度参数

Vai*_*wal 5 java testng

我一直在TestNG上写测试.我的目标是为测试方法提供可变长度参数.我正面临一个对我没有任何意义的问题.代码如下:

@DataProvider(name = "testData")
public static Object[][] testDataProvider() {
    return new Object[][] {
        {
            "hello",
            "bye"
        }
        {
            "hey"
        }
    };
}

@Test(dataProvider = "testData", DataProviderClass = TestData.class)
public void test(String... strings) {
    if (strings.length == 1) {
        // do something
    }
    else {
        // do something
    }
}
Run Code Online (Sandbox Code Playgroud)

这段代码给了我IllegalArgumentException.

  1 java.lang.IllegalArgumentException: argument type mismatch
  2     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  3     at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
  4     at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  5     at java.lang.reflect.Method.invoke(Method.java:606)
  6     at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:84)
  7     at org.testng.internal.Invoker.invokeMethod(Invoker.java:714)
  8     at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:901)
  9     at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1231)
 10     at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:127)
 11     at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:111)
 12     at org.testng.TestRunner.privateRun(TestRunner.java:767)
 13     at org.testng.TestRunner.run(TestRunner.java:617)
 14     at org.testng.SuiteRunner.runTest(SuiteRunner.java:334)
 15     at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:329)
 16     at org.testng.SuiteRunner.privateRun(SuiteRunner.java:291)
 17     at org.testng.SuiteRunner.run(SuiteRunner.java:240)
 18     at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
 19     at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
 20     at org.testng.TestNG.runSuitesSequentially(TestNG.java:1224)
 21     at org.testng.TestNG.runSuitesLocally(TestNG.java:1149)
 22     at org.testng.TestNG.run(TestNG.java:1057)
 23     at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:111)
 24     at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:204)
 25     at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:175)
Run Code Online (Sandbox Code Playgroud)

有人可以告诉我为什么会出现这个错误,我该如何解决这个问题呢?

Anu*_*ony 8

请尝试使用正确的数组初始化,它应该工作.我尝试了相同的代码只是正确的数组初始化,它工作.

@DataProvider(name = "testData")
    public static Object[][] testDataProvider() {
        return new Object[][] {
            new String[]{ "abc", "abcd" },
            new String[]{ "abc", "abcd", "123" }
        };
    }

    @Test(dataProvider = "testData")
    public void test(String... str) {
        System.out.println("The Length is" + str.length);

    }
Run Code Online (Sandbox Code Playgroud)

还附上TestNG结果...... 在此输入图像描述

希望这可以帮助