自定义Java异常失败的JUnit测试

时间:2017-03-19 02:24:43

标签: java exception junit

我正在进行一个JUnit测试,它接受一个Person并检查是否返回了PersonException(我的自定义异常)。 PersonException扩展Exception,Person有一个方法SetDOB(),如果个人超过100,则会抛出PersonException。到目前为止,异常会在控制台中打印,因为它应该,但由于某种原因仍然无法通过测试。这是相关的代码。

//JUnit Test
@Test(expected = PersonException.class)
public void testBadShieffer1() {
    Staff wrongShieffer = new Staff("Bob", "Lloyd", "Shnieffer",
        new Date(1737, 2, 25), "Shieffer Lane", "21277777778" /*PhoneNumber*/ ,
        "RadioMan@shieffer.shief",
        "Radio time.", 10, 500000.00, new Date(1991 + 1900, 1, 1), eTitle.MR);
    //This constructor calls SetDOB()
    fail("No PersonExceptions were thrown.");
}

//setDOB
public void setDOB(Date DOB) {
    try {
        if (((new Date()).getYear() + 1900) > DOB.getYear() + 100)
            throw new PersonException(this);
        else
            this.DOB = DOB;
    } catch (PersonException p) {
        System.out.println(p + " is over 100 years old!");
    }
}

//PersonException class
public class PersonException extends Exception {
    private Person p;

    public PersonException() {
        super();
    }

    public PersonException(String message) {
        super(message);
    }

    public PersonException(Person p) {
        super(p.getLastName());
        this.p = p;
    }

    public Person P() {
        return p;
    }
}

如果这有点长,我道歉,但我相信那里需要的一切都存在。在此先感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

正如我的评论中所述,测试用例永远不会通过,因为抛出的异常也被捕获在同一个方法中(这没有多大意义)。您可以通过以下两种方法之一来解决这个问题,它取决于您想要抛出的异常类型。在调用setDOB()的任何地方都需要捕获并处理 Checked Exception 。您可以通过将setDOB更改为:

来实现此目的
public void setDOB(Date DOB) throws PersonException {

    if (((new Date()).getYear() + 1900) > DOB.getYear() + 100) {
            throw new PersonException(this);
    }
    else {
        this.DOB = DOB;
    }
}

另一种解决方法是将PersonException设为未经检查的例外。这种类型的例外不需要在通话时被捕获。您可以通过将setDOB()更改为:

来实现此目的
 public void setDOB(Date DOB) {

    if (((new Date()).getYear() + 1900) > DOB.getYear() + 100) {
            throw new PersonException(this);
    }
    else {
        this.DOB = DOB;
    }
}

然后PersonException延伸RuntimeException,而不是Exception,如下所示:

public class PersonException extends RuntimeException

要使您的单元测试按原样传递,未经检查方法将起作用。您可以详细了解例外here