JUnit testmethod可以有一个参数吗?
import java.util.regex.Pattern; public class TestUI { private static Pattern p = Pattern.compile("^[A-Za-z0-9()+-]+$"); public static void main(String[] args) { // Test case1 String[] str=test(); System.out.println(str[0]+str.length); match("Alphanumeric(Text)"); } private static String[] test() { boolean res; String[] array={"a","b","c","d","e"}; for(int i=0;i<array.length;i++){ System.out.println(match(array[i])); res=match(array[i]); if(res=true) calltomethod(array); } return array; } private static boolean match(String s) { return p.matcher(s).matches(); } }
在上面的代码中,我需要将数组作为参数传递给JUnit方法,上面的代码将出现在JUnit类中,我可以在JUnit类中使用这些方法,使用带参数的test =方法吗?
您应该查看参数化unit testing(在JUnit 4中引入)。
Daniel Mayer的博客就是一个例子。
另一个更简单的例子是mkyong的网页
是的,您可以使用JUnit 4.4中的Theories
Runner
@RunWith(Theories.class) public class TheorieTest { @DataPoints public static String[] strings={"a","b","c","d","e"}; private static Pattern p = Pattern.compile("^[A-Za-z0-9()+-]+$"); @Theory public void stringTest(String x) { assertTrue("string " + x + " should match but does not", p.matcher(x).matches()); } }
更多细节:
- Junit 4.4发行说明
- 博客
是的,它可以。 最近我开始了zohhak项目。 它可以让你写:
@TestWith({ "25 USD", "38 GBP", "null" }) public void testMethod(Money money) { ... }
您无法使用JUnit直接将参数传递给测试方法。 但是TestNG允许它:
//This method will provide data to any test method that declares that its Data // Provider is named "test1" @DataProvider(name = "test1") public Object[][] createData1() { return new Object[][] { { "Cedric", new Integer(36) }, { "Anne", new Integer(37)}, }; } //This test method declares that its data should be supplied by the Data Provider //named "test1" @Test(dataProvider = "test1") public void verifyData1(String n1, Integer n2) { System.out.println(n1 + " " + n2); }
将打印:
Cedric 36 Anne 37