如何测试应该返回特定日期的Date函数 [英] How to test Date functions that should return a specific date

查看:168
本文介绍了如何测试应该返回特定日期的Date函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下功能:

public static Date getFirstOfLastMonth() {
    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.MONTH, -1);
    cal.set(Calendar.DAY_OF_MONTH, 1);

    return cal.getTime();
}

我如何编写单元测试来检查此函数返回的值是与使用相同的逻辑产生期望值相同的期望值?

How would I write a unit test to check the value returned by this function is the same as the expected value without using the same logic to generate the expected value?

推荐答案

请参阅其他答案以推荐使用JodaTime或Java 8.但是这可以使用java.util.Calendar来完成。

See other answer for recommendation to use JodaTime or Java 8. However this can be done using java.util.Calendar.

关键是改变方法传递日期,而不是让它假定当前时间。也许考虑重新命名这个方法来反映其新的语义,参见Andreas的建议 getFirstOfPreviousMonth

The key is to change your method to pass in the date rather than let it assume the current time. Perhaps consider renaming this method too to reflect its new semantics, see Andreas suggestion of getFirstOfPreviousMonth.

你需要称为 getFirstOfLastMonth(new Date())以保留现有行为,甚至可以使用默认方法

You would need to call this as getFirstOfLastMonth(new Date()) to preserve existing behaviour, perhaps even with default method

public static Date getFirstOfLastMonth() {
     return getFirstOfPreviousMonth(new Date());
}

public static Date getFirstOfPreviousMonth(Date now) {
    Calendar cal = Calendar.getInstance();
    cal.setTime(now);
    cal.add(Calendar.MONTH, -1);
    cal.set(Calendar.DAY_OF_MONTH, 1);

    return cal.getTime();
}

然后一些测试,您可以使用Calendar来检查结果:

Then some tests, you can use Calendar to inspect the result:

@Test
public void previousYear() {
    Calendar input = Calendar.getInstance();
    input.clear();
    input.set(2009, Calendar.JANUARY, 5);

    Date result = getFirstOfLastMonth(input.getTime());

    Calendar output = Calendar.getInstance();
    output.setTime(result);
    assertThat(output.get(Calendar.YEAR), is(2008));
    assertThat(output.get(Calendar.MONTH), is(Calendar.DECEMBER));
    assertThat(output.get(Calendar.DAY_OF_MONTH), is(1));
}

这篇关于如何测试应该返回特定日期的Date函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆