如何将日期的Junit测试用例写入字符串格式化程序方法?

问题描述 投票:0回答:1

这是为以下方法编写junit测试用例的正确方法:

public static String formatDate(Date date) {

        String str = null;

        if(date == null){

            str = new SimpleDateFormat("yyyy MM dd HH:mm:ss").format(new Date());
        }
        else{
            str = new SimpleDateFormat("yyyy MM dd HH:mm:ss").format(date);
        }

        return str;
    }

    @Test
    public void testFormatDate() {
        Date date = new Date();
        String actualDate = DateUtils.formatDate(date);
        System.out.println(actualDate);
        assertEquals(new SimpleDateFormat("yyyy MM dd HH:mm:ss").format(date), actualDate);

    }

对我来说,设置预期日期的方式感觉不对。你怎么说?

junit junit4
1个回答
0
投票

我认为您的考试没有任何问题。只要预期的日期格式与实施中的格式匹配即可。这是要测试的断言目标。

我只建议做一些重构,以便更好

public static String formatDate(Date date) {
    Date dateToBeFormatted = date != null ? date : new Date();
    return new SimpleDateFormat("yyyy MM dd HH:mm:ss").format(dateToBeFormatted);
}

/* Assume the below code block in a separate test file  */
@Test
public void testFormatDate() {
    Date date = new Date();
    System.out.println(actualDate);

    String expectedDateFormat = "yyyy MM dd HH:mm:ss";
    String expectedResult = generateExpectedDateWithFormat(expectedDateFormat, date);

    String actualDate = DateUtils.formatDate(date);
    assertEquals(expectedResult, actualDate);
}

private String generateExpectedDateWithFormat(String dateFormat, Date date) {
    return new SimpleDateFormat(dateFormat).format(date)
}
© www.soinside.com 2019 - 2024. All rights reserved.