【问题标题】:Forcing a JAXBException in JUnit test在 JUnit 测试中强制出现 JAXBException
【发布时间】:2019-03-06 17:14:34
【问题描述】:

我正在尝试为解组方法进行 JUnit 异常测试。

这是我的解组方法(注意:我返回一个字符串,因为正常测试使用预期字符串解组测试)。

public String UnMarshalling(String FILE)
{
    ArrayList<Player> playerList = new ArrayList<Player>();
    try {
        JAXBContext context = JAXBContext.newInstance(Match.class);
        Unmarshaller um = context.createUnmarshaller();
        Match Match2 = (Match) um.unmarshal(new InputStreamReader(new FileInputStream(FILE), StandardCharsets.UTF_8));
        playerList = Match2.playerList;
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (JAXBException e) {
        e.printStackTrace();
    }

    return playerList.toString();
}

这里是这个方法的测试。

@Test
public void unMarshallingTest() {
    assertTrue(marshalling.UnMarshalling(matchxml).contains("Petras"));
}

@Test(expected=JAXBException.class)
public void marshallingTestException()
{
        marshalling.UnMarshalling(matchbrokenxml);    
}

我想要实现的是发送损坏的 xml,例如使用错误版本的 xml 并获取 JAXBException。

到目前为止,我已经在互联网上搜索了一个示例,但一无所获。关于如何实现这一点的任何建议?

【问题讨论】:

  • 那么您没有得到预期的异常吗?如果matchbrokenxml 指向一个包含垃圾的文件,我希望它可以工作。你的文件内容是什么?
  • xml 文件为空,我得到 javax.xml.bind.UnmarshalException
  • 所以我应该将预期的异常更改为 UnmarshalException ?
  • 还有 20 个异常与该 unmarshalexception 相关联。
  • 我应该如何抛出那个异常呢? @glytching

标签: java exception junit


【解决方案1】:

您正在捕获并吞下异常,即 UnMarshalling() 永远不会抛出 JAXBException(或其任何子类)。

这将起作用:

public String UnMarshalling(String FILE) throws JAXBException {
    ArrayList<Player> playerList = new ArrayList<Player>();
    try {
        JAXBContext context = JAXBContext.newInstance(Match.class);
        Unmarshaller um = context.createUnmarshaller();
        Match Match2 = (Match) um.unmarshal(new InputStreamReader(new FileInputStream(FILE), StandardCharsets.UTF_8));
        playerList = Match2.playerList;
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } 

    return playerList.toString();
}


@Test(expected=UnmarshalException.class)
public void marshallingTestException() {

    marshalling.UnMarshalling(matchbrokenxml);

}

这里的主要变化是删除了JAXBException 的catch 子句,并将throws JAXBException 添加到方法声明中。

您的测试强烈表明 JAXBException 是此方法的公共 API 的一部分,在这种情况下,声明抛出 JAXBEception 的方法是有意义的。另一方面,如果您真的不希望或不需要方法签名中的JAXBException,那么您的测试用例要么是多余的,要么正在处理错误的异常类型。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-09
    • 2023-03-06
    • 2012-05-20
    • 1970-01-01
    • 2018-04-09
    • 2015-11-20
    相关资源
    最近更新 更多