如何使用单元测试测试我的自定义异常

zpf6vheq  于 2021-07-06  发布在  Java
关注(0)|答案(2)|浏览(330)

你好,我已经为我的逻辑写了一个测试用例,所有这些都很好地工作。但是,我不知道如何测试我的自定义异常。我的代码如下;

@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");
}
ghhaqwfi

ghhaqwfi1#

该异常已在planefactory.getplane(planetype)中发生,因此事后检查该异常不起作用。
我更喜欢@rule expectedexception方法,因为它很灵活。例如,您还可以检查自定义创建的错误消息以查找自己的异常。在您的情况下,这是“您没有输入任何东西来检查飞机”。

@Rule
public ExpectedException thrown= ExpectedException.none();

@Test
public void testPlaneFactory_isEmptyOrNull_ThenReturnException() {
    thrown.expect(PlaneTypeNotFoundException.class);
    thrown.expectMessage("You have not enter anything to check a plane"); // check only for a substring is also possible

    PlaneFactory planeFactory = new PlaneFactory();

    String planeType = "";
    LightJet lightJet = (LightJet) planeFactory.getPlane(planeType);

    //not needed
    //assertThrows(PlaneNotFoundException.class, () -> lightJet.getType().equalsIgnoreCase(planeType), "You have not enter anything to check a plane");

}
sdnqo3pr

sdnqo3pr2#

如果我正确地遵循了您的代码,那么 assertThrows() 应该是您希望生成异常的代码:

public void testPlaneFactory_isEmptyOrNull_ThenReturnException() {
    assertThrows(PlaneNotFoundException.class, () -> planeFactory.getPlane(""));
}

如果它确实抛出异常,那么测试应该通过。
第二种情况的测试是:

void testInvalidPlaneType() {
    assertThrows(InvalidPlaneTypeException.class, () -> planeFactory.getPlane("doh"));
}

相关问题