Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting EasyMock mock objects to throw Exceptions

Tags:

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.

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.

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.

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.

Anyone done anything like this with EasyMock before?

References

  • EasyMock API
like image 342
Jon Avatar asked Feb 17 '11 10:02

Jon


People also ask

Is EasyMock a mocking framework?

EasyMock is a mocking framework, JAVA-based library that is used for effective unit testing of JAVA applications. EasyMock is used to mock interfaces so that a dummy functionality can be added to a mock interface that can be used in unit testing.


2 Answers

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")); 
like image 143
Péter Török Avatar answered Sep 30 '22 18:09

Péter Török


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); 
like image 44
Augusto Avatar answered Sep 30 '22 18:09

Augusto