gpt4 book ai didi

java - 在 JUnit 测试中强制出现 JAXBException

转载 作者:太空宇宙 更新时间:2023-11-04 09:49:02 26 4
gpt4 key购买 nike

我正在尝试对解码方法进行 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

到目前为止,我已经在互联网上寻找了一个例子,但一无所获。关于如何实现这一目标有什么建议吗?

最佳答案

您正在捕获并吞下异常,即 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是此方法的公共(public)API的一部分,在这种情况下,声明抛出JAXBEception的方法是有意义的。另一方面,如果您确实不希望或需要方法签名中的 JAXBException,那么您的测试用例要么是多余的,要么正在解决错误的异常类型。

关于java - 在 JUnit 测试中强制出现 JAXBException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55028702/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com