我为我的应用程序编写了几个JUnit类,但是现在我想将我的测试数据(现在是硬编码的)从代码中分离出来,变成只有数据的文本文件/属性文件/xml/任何东西。
因此,我可以轻松地给出各种测试数据,而无需修改我的JUnit。
我正在考虑将它们放入一个文本文件中,并在我的JUnit套件一开始就使用解析器来解析它,并将所有数据转换为Java静态类常量,这样我就可以轻松地在JUnit中的任何地方引用它。
public final class TestDataConstants {
public static final String username = "xbeta";
public static final String password = "test123!";
public static final String authToken = "f17bf9c8-9d38-47af-a053-210130cac6f7";
...
}现在我知道我可以很容易地为这个问题编写一个解析器,但是我要为那些过去有经验的人问两个问题。
动态生成Java代码。
谢谢你的进阶。
发布于 2012-05-31 23:15:32
一种方法是使用.properties文件,然后在测试开始时将其作为资源加载。
例如,
test.properties:
test.username=xbeta
test.password=test123!
test.authToken=f17bf9c8-9d38-47af-a053-210130cac6f7然后,在测试中,假设test.properties文件位于类路径上,则可以使用如下所示的内容访问数据:
// note, the .properties is removed in the call to .getBundle
ResourceBundle testProperties = ResourceBundle.getBundle("test");
String username = testProperties.getString("test.username");
String password = testProperties.getString("test.password");发布于 2012-06-01 05:24:24
假设您将数据放入属性文件中,下面是如何使用@DataProvider实现此操作的:
public class A {
@Test(dataProvider = "dp")
public void test(String k, String v) {
System.out.println("Testing " + k + " " + v);
Assert.assertEquals(k.toUpperCase(), v);
}
@DataProvider
public Object[][] dp() throws FileNotFoundException, IOException {
Properties p = new Properties();
p.load(new FileInputStream(new File("/tmp/a.properties")));
List<Object[]> result = Lists.newArrayList();
for (Map.Entry<Object, Object> es : p.entrySet()) {
result.add(new Object[] { es.getKey(), es.getValue() });
}
return result.toArray(new Object[result.size()][]);
}
@Test(dataProvider = "dp")
public void test(String k, String v) {
System.out.println("Testing " + k + " " + v);
Assert.assertEquals(k.toUpperCase(), v);
}
}属性文件:
abc: ABC
def: DEF
ghi: GHI以及产出:
Testing abc ABC
Testing def DEF
Testing ghi GHI
PASSED: test("abc", "ABC")
PASSED: test("def", "DEF")
PASSED: test("ghi", "GHI")
===============================================
Test1
Tests run: 3, Failures: 0, Skips: 0
===============================================注意,每个参数集都传递给测试方法(因此测试方法被调用了三次),并且该测试方法将这些参数声明为常规方法参数。
关于数据提供程序的更多详细信息:http://testng.org/doc/documentation-main.html#parameters-dataproviders
https://stackoverflow.com/questions/10842400
复制相似问题