我有一个方法,如果名称与正则表达式匹配,则必须返回 true;如果名称包含特殊字符或数字,则必须返回 null。
这是方法:
@SuppressWarnings("null")
public boolean containsSpecialCharacters(String text) {
Pattern p = Pattern.compile("/^[a-zA-Z\\s]+$/");
//check if the name has special characters
Matcher m = p.matcher(text);
boolean b = m.find();
//cast the null to boolean
Boolean boolean1 = (Boolean) null;
if (m.matches()) {
return true;
}
else {
return boolean1;
}
}
这是无法通过的方法的测试:
@Test
public void parseBeanCheck() throws NumberFormatException, IOException, SAXException, IntrospectionException {
IngenicoForwardingHelper helper = new IngenicoForwardingHelper();
String test1 = "Steve Jobs";
Assert.assertTrue(helper.containsSpecialCharacters(test1));
//This should return Null
String test2 = "Steve Jobs1";
Assert.assertNull(helper.containsSpecialCharacters(test2));
//This should return Null
String test3 = "Steve Jöbs";
Assert.assertNull(helper.containsSpecialCharacters(test3));
}
最佳答案
您的方法返回一个 boolean
,它是一种原始类型,只允许值 true
和 false
。它不允许 null
,因此您的 assertNull()
测试将永远无法工作!
您可以更改方法签名以返回 Boolean
,但如果可能的话,通常最好避免从方法返回 null
。无论如何,返回 true
或 false
比返回 true
或 null
更有意义。
在 Java 中,您的正则表达式不需要(也不应该)在开始和结束处使用斜线。
您可以将代码更改为如下内容:
public boolean containsSpecialCharacters(String text) {
Pattern p = Pattern.compile("^[a-zA-Z\\s]+$");
Matcher m = p.matcher(text);
return !m.matches();
}
或者更简单:
public boolean containsSpecialCharacters(String text) {
return !text.matches("[a-zA-Z\\s]+");
}
测试是这样的:
@Test
public void parseBeanCheck() throws NumberFormatException, IOException, SAXException, IntrospectionException {
IngenicoForwardingHelper helper = new IngenicoForwardingHelper();
Assert.assertFalse(helper.containsSpecialCharacters("Steve Jobs"));
Assert.assertTrue(helper.containsSpecialCharacters("Steve Jobs1"));
Assert.assertTrue(helper.containsSpecialCharacters("Steve Jöbs"));
}
还值得一提的是,\s
不仅会匹配空格,还会匹配制表符、换行符、回车符等。因此请确保这是您想要的。
关于Java JUnit 测试未通过,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48278628/