我有一个方法,如果名称与正则表达式匹配,则必须返回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,它是仅允许值truefalse的原始类型。它不允许null,因此您对assertNull()的测试将永远无法进行!

您可以将方法签名更改为返回Boolean,但是通常最好避免从方法中返回null。无论如何,返回truefalsetruenull更有意义。

在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不仅将匹配空格,而且还将匹配制表符,换行符,回车符等。因此请确保这正是您想要的。

10-07 13:24
查看更多