Java正则表达式的单元测试,以匹配Wed,Sep 15(XXX,XXX ##)未通过

时间:2015-09-10 01:57:25

标签: java regex junit junit4

我正在尝试匹配匹配“XXX,XXX ##”

等内容的正则表达式

所以我尝试了这个:"\\w{3},\\s\\w{3}\\s\\d{2}"但它无效

包括完整代码,这是我正在尝试测试的方法:

public String formatDate(String instruction) {
    Date date = new Date();

    SimpleDateFormat format = new SimpleDateFormat();

    if (instruction.equalsIgnoreCase("short")) {
        format = new SimpleDateFormat("EEE, MMM yy");
    }
    else if (instruction.equalsIgnoreCase("full")) {
        format = new SimpleDateFormat("EEEE, MMMM yyyy");
    }

    String dateToString = format.format(date);
    //Log.e("exe", dateToString);

    return dateToString;
}

这是单元测试:

public class SchedulerDateTest {
    SchedulerDate schedulerDate;

    @Before
    public void setUp() throws Exception {
        schedulerDate = new SchedulerDate();
    }

    //....

    @Test
    public void testFormatDate() throws Exception {
        assertTrue("if parameter is short I want to receive the date in a short format for example: Wed, Sep 15",
            schedulerDate.formatDate("short")
                    .matches("\\w{3},\\s\\w{3}\\s\\d{2}");
    }
}

1 个答案:

答案 0 :(得分:2)

在撰写问题时,请将其设为 Minimal,Complete,and Verifiable 。见https://stackoverflow.com/help/mcve

这就是以上所有内容:

Date date = new Date();
System.out.println("date = " + date);
SimpleDateFormat format = new SimpleDateFormat("EEE, MMM yy");
String dateToString = format.format(date);
System.out.println("dateToString = '" + dateToString + "'");
System.out.println("matches = " + dateToString.matches("\\w{3},\\s\\w{3}\\s\\d{2}"));

输出

date = Wed Sep 09 22:16:21 EDT 2015
dateToString = 'Wed, Sep 15'
matches = true

通过打印中间值,您将能够看到出现问题的地方。

这可能是您的语言问题,例如:如果我切换Locale

Locale.setDefault(Locale.CANADA_FRENCH);

输出

date = Wed Sep 09 22:19:17 EDT 2015
dateToString = 'mer., sept. 15'
matches = false