获取EasyMock模拟对象以抛出异常 [英] Getting EasyMock mock objects to throw Exceptions

查看:288
本文介绍了获取EasyMock模拟对象以抛出异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm in process of using EasyMock to write Unit tests for a number of collaborating classes. One of these classes (lets call it Foo) opens a network connection to a remote server and parses that servers' XML response into something the rest of the classes can use.

目前,我的测试仅包含一切都很糟糕且远程服务器已启动并运行并按预期返回XML的场景。但是,如果我可以模拟 Foo ,我更快乐,这样我就可以模拟远程服务器停机时会发生什么,或者还有其他问题导致 IOException Foo 抛出。

Presently my tests only encompass scenarios in which everything is hunky-dory and the remote server is up and running and returning XML as expected. However, I would be happier if I could mock Foo so that I simulate what happens if the remote server is down, or there is some other problem that causes an IOException to be thrown by Foo.

我已经看过EasyMock API了,我看不到任何看起来像是要求模拟抛出异常的方法。

I have had a look at the EasyMock API, and I can't see anything that looks like a method asking a mock to throw an Exception.

对于基于 Exception 的测试,我并不是绝对必要的,但我很好奇是否可以使用EasyMock,而且我认为以这种方式测试 Foo 的公共合同会很有用。

It's not absolutely essential for me to have Exception based tests, but I am curious if its possible with EasyMock, and I think it would be useful to test Foo's public contract in this way.

之前有人用EasyMock做过这样的事吗?

Anyone done anything like this with EasyMock before?

参考资料

  • EasyMock API

推荐答案

来自文档


用于指定例外(更确切地说: Throwable s)抛出, expectLastCall()期望返回的对象(T值) )提供方法 andThrow(Throwable throwable)。在调用Mock对象之后,必须在记录状态下调用该方法,它指定要抛出的 Throwable

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.

可以从每个方法抛出未经检查的异常(即 RuntimeException 错误及其所有子类) 。只能从实际抛出它们的方法抛出已检查的异常。

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"));

这篇关于获取EasyMock模拟对象以抛出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆