这是为以下方法编写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);
}
对我来说,设置预期日期的方式感觉不对。你怎么说?
我认为您的考试没有任何问题。只要预期的日期格式与实施中的格式匹配即可。这是要测试的断言目标。
我只建议做一些重构,以便更好
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)
}