如何单元测试日期相关方法?

时间:2017-06-20 09:30:14

标签: java unit-testing java-8

我有一个像下面这样的方法,

public static boolean isBetweenMonthDays(int startDayOfMonth,
        int endDayOfMonth) {

    LocalDate today = LocalDate.now();

    if (today.getDayOfMonth() >= startDayOfMonth
        && today.getDayOfMonth() <= endDayOfMonth) {
        return true;
    }

    return false;
    }

这是实用程序类中的一个简单方法,但是还有许多其他复杂的方法,结果依赖于今天的日期,所以我的断言在某些日期会失败。

对这种方法进行单元测试最好是什么?

更新:这些以下类型的单元测试被视为不良做法,因为大多数人都在建议注入LocalDate依赖关系&amp;使课堂可测试?

我这样做是犹豫不决的,因为它是静态实用程序类,而客户端只对整数有效?

@Test
    public void testIsBetweenMonthDays_success_true() {

    LocalDate today = LocalDate.now();

    boolean result = ResponseMatchingUtil.isBetweenMonthDays(10, 25);

    if (today.getDayOfMonth() >= 10 && today.getDayOfMonth() <= 25)
        assertTrue(result);
    else
        assertFalse(result);

    }

    @Test
    public void testIsBetweenMonthDays_success_false() {

    LocalDate today = LocalDate.now();

    boolean result = ResponseMatchingUtil.isBetweenMonthDays(4, 10);

    if (today.getDayOfMonth() >= 4 && today.getDayOfMonth() <= 10)
        assertTrue(result);
    else
        assertFalse(result);

    }

1 个答案:

答案 0 :(得分:1)

重构它以使其变得可测试:

public static boolean isBetweenMonthDays(int startDayOfMonth,
        int endDayOfMonth, LocalDate date) {

    if (date.getDayOfMonth() >= startDayOfMonth
        && date.getDayOfMonth() <= endDayOfMonth) {
        return true;
    }

    return false;
    }

public static boolean isBetweenMonthDays(int startDayOfMonth,
        int endDayOfMonth) {

    return isBetweenMonthDays(startDayOfMonth, endDayOfMonth, LocalDate.now());
    }