我必须在100+不同的情况下进行测试,对于每一种情况,我都需要读取和分析外部xml。我用:
String xml = IOUtils.toString(
this.getClass().getResourceAsStream(path),encoding);例如,我的测试xml:
<container xmlns:dmc="http://example.com/common">
<object id="1369" checkedParamter="in" class="Class1">
...
</object>
</container>但是我必须用有效的id、缺少的id和现有的id进行测试。然后,我需要checkedParamter有3-4个值,并将所有的组合与id属性结合起来。对于现在的每个测试,我都创建了新的checkedParamter. xml,唯一的区别是这两个属性:、id、和。我想知道是否有简单的方法可以读取xml和使用相同的结构,但是可以通过测试中的这些值。
<container xmlns:dmc=" http://example.com/common">
<object id= ${valueId} checkedParamter=${valueChechedParamter} class="Class1">
...
</object>
</container>然后,我将使用一个xml,并将愿望值放在测试的开始。我没有技术或方法去做这件事吗?
发布于 2016-02-01 09:51:47
最好的方法是使用${valueId}拥有一个单独的文件,就像您已经拥有的那样。
我们将使用JUnit的以下特性来实现我们的目标:
我们将以下文件存储到项目的resources部分:
<container xmlns:dmc=" http://example.com/common">
<object id= ${valueId} checkedParamter=${valueChechedParamter} class="Class1">
...
</object>
</container>然后我们开始测试:
@RunWith(Parameterized.class)
public class XmlInputTest {
@Parameters
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][] {
{ 1369, "in" },
{ 1369, "out" },
{ 753, "in" },
// etc....
});
}
@Parameter(value = 0)
public int id;
@Parameter(value = 1)
public String checkedParamter;
@Test
public void mainTest() {
String xml = IOUtils.toString(
this.getClass().getResourceAsStream("template.xml"),encoding);
xml = xml.replace("${valueId}",String.valueOf(id)).replace("${valueChechedParamter}",checkedParamter);
// remaing test....
}
}使用这种测试运行方法的优点是,您有一个要测试的输入的简单列表。
发布于 2016-02-01 09:51:27
您可以在测试开始时尝试这样的方法。
Map<String,String> properties = new HashMap<String, String>();
properties.put("valueId", "1");
properties.put("valueChechedParamter", "0");
String propertyRegex = "\\$\\{([^}]*)\\}";
Pattern pattern = Pattern.compile(propertyRegex);
int i = 0;
Matcher matcher = pattern.matcher(xml);
StringBuilder result = new StringBuilder(xml.length());
while(matcher.find()) {
result.append(expression.substring(i, matcher.start()));
String property = matcher.group();
property = property.substring(2, property.length() - 1);
if(properties.containsKey(property)) {
property = properties.get(property);
} else {
property = matcher.group();
}
result.append(property);
i = matcher.end();
}
result.append(expression.substring(i));
String resultXml = result.toString();https://stackoverflow.com/questions/35127124
复制相似问题