Java 如何使用单元测试测试我的自定义异常
您好,我已经为我的逻辑编写了一个测试用例,所有这些都很好地工作。然而,我不知道如何测试我的自定义异常。我的代码如下Java 如何使用单元测试测试我的自定义异常,java,spring,junit,java-8,mocking,Java,Spring,Junit,Java 8,Mocking,您好,我已经为我的逻辑编写了一个测试用例,所有这些都很好地工作。然而,我不知道如何测试我的自定义异常。我的代码如下 @Component public class PlaneFactory { public Plane getPlane(String planeType) { if (StringUtils.isBlank(planeType)) { throw new PlaneTyp
@Component
public class PlaneFactory {
public Plane getPlane(String planeType) {
if (StringUtils.isBlank(planeType)) {
throw new PlaneTypeNotFoundException();
}
if (planeType.equalsIgnoreCase("lightJet")) {
return new LightJet();
} else if (planeType.equalsIgnoreCase("midJet")) {
return new MidJet();
}
else {
throw new InvalidPlaneTypeException();
}
my custom exceptions below;
PlaneTypeNotFoundException class below;
public class PlaneTypeNotFoundException extends RuntimeException {
private static final long serialVersionUID = 4314211343358454345L;
public PlaneTypeNotFoundException() {
super("You have not enter anything to check a plane");
}
}
InvalidPlaneTypeException below;
public class InvalidPlaneTypeException extends RuntimeException {
public InvalidPlaneTypeException() {
super("You need to enter one of following plane types : {LightJet, MidJet}");
}
}
哪些方法适合使用?我的意思是在这个场景中,我应该使用assertThrows还是只使用预期的注释
对于PlaneTypeNotFoundException,我尝试了一些在其下不起作用的方法
@Test
public void testPlaneFactory_isEmptyOrNull_ThenReturnException() {
String planeType = "";
LightJet lightJet= (LightJet) planeFactory.getPlane(planeType);
assertThrows(PlaneNotFoundException.class, () -> lightJet.getType().equalsIgnoreCase(planeType), "You have not enter anything to check a plane");
}
如果我正确地遵循您的代码,则
assertThrows()
中的可执行lambda应该是您希望生成异常的代码:
public void testPlaneFactory_isEmptyOrNull_ThenReturnException() {
assertThrows(PlaneNotFoundException.class, () -> planeFactory.getPlane(""));
}
如果它确实抛出异常,那么测试应该通过
第二种情况的测试将是:
void testInvalidPlaneType() {
assertThrows(InvalidPlaneTypeException.class, () -> planeFactory.getPlane("doh"));
}
不用担心,JUnit在测试异常时总是有点古怪。