【发布时间】: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