views:

144

answers:

3

I'm using EasyMock to create mock objects for JUnit testing in Java. I create a mock object and pass it to another thread where it expects methods to be called. In the other thread, the calls are enclosed in a try/catch(Throwable) block, so when an unexpected call occurs on the mock and it thus throws AssertionError, that error is caught by the catch block and treated. So, even though an unexpected call occurred, the test passes.

In order to have the test fail as expected, I would like to delay all verification of calls to the EasyMock.verify(mock) call made in the test-runner thread at the end. Is this possible and how?

A: 

The correct solution I'd guess is to stop catching Throwable. Doing so catches all Errors as you're finding, which can be quite dangerous... are you absolutely positively 100% sure you need to catch Throwable? Why?

(If it turns out you do, you could catch AssertionError specifically and rethrow it. But that's ugly!)

Steven Schlansker
We catch Throwable (ugly, I agree) so we can intercept (e.g.) Out-of-memory errors and do some logging and restart the app cleanly from that point. I'll maybe resort to catching AssertionError if no other solution is available.
Philipp
@Steven - catching AssertionError and rethrowing it is almost certainly less ugly than an unconditional `catch (Throwable t)` block. :-)
Andrzej Doyle
+1  A: 

I'm not sure about how to do this with EasyMock, but this behavior is possible with Mockito because verification assertions can be specified at the end of the test.

deterb
A: 

Try using nice mocks:

http://easymock.org/EasyMock2_5_2_Documentation.html

"Nice Mocks On a Mock Object returned by createMock() the default behavior for all methods is to throw an AssertionError for all unexpected method calls. If you would like a "nice" Mock Object that by default allows all method calls and returns appropriate empty values (0, null or false), use createNiceMock() instead. "

Default values will be returned for unexpected calls instead of throwing AssertionError, but you can still verify them with the verify() method (in which case the AssertionErrors will be thrown)

seibzhen
I also agree with deterb's suggestion: Mockito does provide a simpler mocking mechanism (i.e not having to worry about nice/strick mocks) and you can verify only the behavior you actually need.
seibzhen
+1: It's not worth switching libraries when your current one provides the functionality you need!
Andrzej Doyle
-1: A nice mock will accept any method call, and thus will not allow to test if unexpected calls happened (only if expected calls did not happen).
Philipp
You're right, haven't seen it that way; I've tried to experiment with it though and could not find a better solution.Perhaps you could try to decrease the granularity of your test such as testing a more specific method.
seibzhen