gpt4 book ai didi

java - 日期检查的基本 JUnit

转载 作者:搜寻专家 更新时间:2023-10-31 20:02:17 26 4
gpt4 key购买 nike

我正在尝试为以下代码编写一个 Junit;

/**
* Check if a date is greater than 24 hours
* @param dateToCheck the date to check
* @return true if it is greater than otherwise false
*/
public static boolean dateGreaterThan24Hours(Date dateToCheck){
if(dateToCheck == null){
throw new IllegalArgumentException("The date passed to check for greater than 24 hours is null");
}
long millisIn24Hours = 1000 * 60 * 60 * 24;
Date hours24ago = new Date(new Date().getTime() - millisIn24Hours);
if (dateToCheck.before(hours24ago)) {
//24 hrs have passed
return true;
}
return false;
}

但是我很难这样做,因为该方法只接受要检查的日期。意味着当前对测试方法的尝试显然会失败;

@Test
public void checkLessThan24HoursShouldReturnTrue(){
//Calendar represents the 7th of July 2014 at 17.30pm
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 2014);
cal.set(Calendar.MONTH, 07);
cal.set(Calendar.DAY_OF_MONTH, 7);
cal.set(Calendar.HOUR_OF_DAY,17);
cal.set(Calendar.MINUTE,30);
cal.set(Calendar.SECOND,0);
cal.set(Calendar.MILLISECOND,0);

Date july7 = cal.getTime();

//Calendar represents the 6th of July 2014 at 18.30pm
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 2014);
cal.set(Calendar.MONTH, 07);
cal.set(Calendar.DAY_OF_MONTH, 6);
cal.set(Calendar.HOUR_OF_DAY,18);
cal.set(Calendar.MINUTE,30);
cal.set(Calendar.SECOND,0);
cal.set(Calendar.MILLISECOND,0);

Date july6 = cal.getTime();
}

谁能建议我如何重构原始方法以使其更易于测试?

谢谢

最佳答案

您不必更改原始方法。最容易编写的测试是:

@Test
public void checkMoreThan24HoursShouldReturnTrue() {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.HOUR_OF_DAY, -25);
assertTrue(YourClass.dateGreaterThan24Hours(cal.getTime()));
}

@Test
public void checkLessThan24HoursShouldReturnFalse() {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.HOUR_OF_DAY, -23);
assertFalse(YourClass.dateGreaterThan24Hours(cal.getTime()));
}

此外,我还建议按照@DaveNewton 在评论中的建议进行一些重构,并进行一个测试来验证您的自定义异常是否为 null 参数。

关于java - 日期检查的基本 JUnit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24805149/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com