Getting EasyMock mock objects to throw Exceptions

怎甘沉沦 提交于 2019-11-29 03:04:24
Péter Török

From the 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.

For example:

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

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

you can use the method andThrow(Throwable throwable) in easy mock. Check the documentation - heading Working with Exceptions.

For example

 expect(mock.voteForRemoval("Document"))
    .andThrow(new RuntimeException(), 4);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!