我有以下单元测试来检查XML行首的缩进:
private static final String REGEX_PATTERN = "^\\s+";
@BeforeTest
@Parameters("unformattedXmlFile")
public void setup(String unformattedXmlFile) throws TransformerException, ParserConfigurationException, InstantiationException, IllegalAccessException, ClassNotFoundException {
EditXmlPanel panel = new EditXmlPanel();
try {
String unformatted = readFile(unformattedXmlFile);
String formatter = panel.prettyFormat(unformatted);
String [] lines = formatter.split("\n");
for(int i=0; i < lines.length; i++) {
System.out.println(lines[i]);
if(i !=0 && i !=lines.length -1) {
//Assert.assertEquals((Character.isWhitespace(lines[i].charAt(0))), true);
Assert.assertEquals(lines[i].matches(REGEX_PATTERN), true);
}
}
} catch (IOException e) {
Assert.fail("Unable to read file: " + e.getMessage(), e);
}
}
我读了一个未格式化的XML文件-没有缩进-然后通过一个函数运行它以漂亮地打印它,例如-正确缩进它。然后,我的单元测试将在每行的开头检查缩进。因此,缩进的行可能如下所示:
<message code="272" coeMsgName="CCR_I-Credit-Control-Initial" endtoend="AUTO" error="false" hopbyhop="AUTO" proxiable="true" request="true" retransmit="false">
我的正则表达式是:
^\\s+
因此,请在行首匹配任意数量的空格。我已经使用regexr.com检查了模式,这似乎还可以,但是断言总是失败。我不明白为什么。
您的正则表达式必须为:
private static final String REGEX_PATTERN = "\\s+.*";
因为String.matches
尝试将全行与您的正则表达式匹配,否则它将返回false。
PS:由于同样的原因,也没有必要使用锚^
,并$
在你的正则表达式。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句