gpt4 book ai didi

java - 让 EasyMock 模拟对象抛出异常

转载 作者:IT老高 更新时间:2023-10-28 20:46:20 26 4
gpt4 key购买 nike

我正在使用 EasyMock 为许多协作类编写单元测试。其中一个类(我们称之为 Foo)打开一个到远程服务器的网络连接,并将服务器的 XML 响应解析为其他类可以使用的东西。

目前,我的测试仅包含以下场景:一切都很正常,远程服务器已启动并运行并按预期返回 XML。但是,如果我可以模拟 Foo 以便模拟远程服务器关闭或其他导致 的问题时会发生什么,我更高兴Foo 抛出的 IOException

我查看了 EasyMock API,但看不到任何看起来像要求模拟抛出异常的方法的东西。

对我来说,基于 Exception 的测试并不是绝对必要的,但我很好奇 EasyMock 是否可能,我认为测试 Foo' 会很有用s 以这种方式公开契约(Contract)。

以前有人用 EasyMock 做过类似的事情吗?

引用文献

最佳答案

来自 documentation :

For specifying exceptions (more exactly: Throwables) to be thrown, the object returned by expectLastCall() and expect(T value) provides the method andThrow(Throwable throwable). The method has to be called in record state after the call to the Mock Object for which it specifies the Throwable to be thrown.

Unchecked exceptions (that is, RuntimeException, Error and all their subclasses) can be thrown from every method. Checked exceptions can only be thrown from the methods that do actually throw them.

例如:

expectLastCall().andThrow(new HibernateException("Something terrible happened"));

expect(query.list()).andThrow(
new HibernateException("Something terrible happened"));

关于java - 让 EasyMock 模拟对象抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5027533/

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