我正在尝试进行一个JUnit测试,以检查Appointment对象的输入是否有效。我已经完成了所有的测试,但是每当我运行测试时,除了一个测试之外,所有的测试都通过了。由于某种原因,测试testDateInThePast()失败了。有人能指出这个问题吗?下面是我的代码:
Appointment.java
package appointment;
import java.util.Date;
public class Appointment {
private String appointmentId;
private Date appointmentDate;
private String description;
public Appointment(String appointmentId, Date appointmentDate, String description) {
if(appointmentId == null || appointmentId.length() > 10) {
//We will want to test for the exception
throw new IllegalArgumentException("Invalid input");
}
if(appointmentDate == null || appointmentDate.before(new Date())) {
throw new IllegalArgumentException("Invalid date");
}
if(description == null || description.length() > 50) {
throw new IllegalArgumentException("Invalid description");
}
this.appointmentId = appointmentId;
this.appointmentDate = appointmentDate;
this.description = description;
}
public String getAppointmentId() {
return appointmentId;
}
public Date getAppointmentDate() {
return appointmentDate;
}
public String getDescription() {
return description;
}
}
AppointmentTest.java
package test;
import static org.junit.jupiter.api.Assertions.*;
import java.util.Calendar;
import java.util.Date;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import appointment.Appointment;
class AppointmentTest {
@SuppressWarnings("deprecation")
@Test
void testAppointment() {
Appointment appointment = new Appointment("12121212", new Date(2023, Calendar.MAY, 26), "This appointment involves a couple things");
assertTrue(appointment.getAppointmentId().equals("12121212"));
assertTrue(appointment.getAppointmentDate().equals(new Date(2023, Calendar.MAY, 26)));
assertTrue(appointment.getDescription().equals("This appointment involves a couple things"));
}
@Test
void testAppointmentIdToLong() {
Assertions.assertThrows(IllegalArgumentException.class, () -> {
new Appointment("121212124545", new Date(2023, Calendar.MAY, 26), "This appointment involves a couple things");
});
}
@SuppressWarnings("deprecation")
@Test
void testDateInThePast() {
Assertions.assertThrows(IllegalArgumentException.class, () -> {
new Appointment("34345612", new Date(2022, Calendar.JUNE, 26), "This appointment involves a couple things");
});
}
@Test
void testAppointmentDescriptionToLong() {
Assertions.assertThrows(IllegalArgumentException.class, () -> {
new Appointment("34345612", new Date(2023, Calendar.MAY, 26), "This appointment description is very long and many people would not bother to read the whole thing and just skip over some parts");
});
}
}
2条答案
按热度按时间z31licg01#
请考虑移至新的java.time.LocalDate
以及:
rwqw0loc2#
您面临的是
java.util.Date#Date(int, int, int)
构造函数的典型陷阱:请注意年份-年份减去1900,也就是说,您在单元测试中使用的所有日期都是遥远的将来。
附言。
我确实认为检查抛出的异常类型是不够的,因为所有三个分支都抛出相同的
IllegalArgumentException
-您还需要检查异常消息。