gpt4 book ai didi

java - JUnit如何处理DateTimeParseException

转载 作者:行者123 更新时间:2023-12-02 02:13:56 26 4
gpt4 key购买 nike

如何使用 JUnit 测试“错误输入”?我试图通过向 Flight 对象的第一个参数传递一个无法解析为 LocalTime 类型的值来实例化 Flight 对象。当我这样做时,JUnit testConstructor 方法中的“失败”给出了错误。我应该如何处理这个异常才能顺利通过 JUnit 测试?谢谢

protected Flight(String scheduledTime, String eventType, String identifier) {
try {
this.scheduledTime = LocalTime.parse(scheduledTime);
this.eventType = EventType.valueOf(eventType);
this.identifier = identifier;
this.actualTime = null;
this.runwayUsed = null;
}
catch(Exception e) {
System.out.println(e + " Flight constructor");
}

} //end of constructor

下面的 try/catch block 中是给出错误的 JUnit 代码。

@Test
public void testConstructor() {

Flight f1 = new Flight("00:00", "ARRIVAL", "A001");
Flight f2 = new Flight("00:00", "DEPARTURE", "D001");

assertEquals(LocalTime.parse("00:00"), f1.getScheduledTime());
assertEquals(EventType.ARRIVAL, f1.getEvent());
assertEquals("A001", f1.getIdent());
assertEquals(null, f1.getActualTime());
assertEquals(null, f1.getRunwayUsed());

assertEquals(LocalTime.parse("00:00"), f2.getScheduledTime());
assertEquals(EventType.DEPARTURE, f2.getEvent());
assertEquals("D001", f2.getIdent());
assertEquals(null, f2.getActualTime());
assertEquals(null, f2.getRunwayUsed());

//invalid entry for scheduledTime
try {
Flight f3 = new Flight("00:0j", "ARRIVAL", "A001");
fail("Expected exception");
} //end of try
catch(Exception e) {
System.out.println(e);
} //end of catch

}

最佳答案

首先,正如 @binoternary 所指出的,你的构造函数不会在自身之外抛出异常,它只是记录它。其次,要使测试仅在引发特定异常时通过,您需要将此注释添加到测试方法中:

@Test(expected = DateTimeParseException.class) // or any other exception class expected to be thrown
public void testException() {
Flight f3 = new Flight("00:0j", "ARRIVAL", "A001");
}

关于java - JUnit如何处理DateTimeParseException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49574964/

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