【发布时间】:2018-01-16 10:03:26
【问题描述】:
如果名称与正则表达式匹配,我有一个方法必须返回 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));
}
【问题讨论】:
-
究竟是什么失败了?这应该怎么做? //将 null 转换为 boolean Boolean boolean1 = (Boolean) null;
-
或者更确切地说,返回 m.matches();
-
@JackFlamp 我感觉那个测试应该会失败
-
@Antony 您的方法似乎不太可能(能够)返回 null。
-
也许让您的返回类型为
Boolean而不是boolean,对于true使用Boolean.TRUE。但我同意@Berger 的观点,为什么你要返回null而不是false?