SpecialEd
SpecialEd

Reputation: 495

EasyMock newbie: how to override a method to behave differently, not just return a different value

I am learning unit testing and mocking. I have JUnit running, and instead of using a Mocking Framework, I have manually created mock classes by extending existing classes and interfaces. I would like to learn the mocking framework EasyMock because thats all thats available here at my work. While you might suggest some other mocking framework, they will not be available to me.

The Setup:

I have a View and a Presenter and a API backend. When the user clicks a button: "Check For Updates", the view calls the presenter.checkForUpdates() which does a call to api.checkForUpdates() and expects an callback. If the an exception occurs, the api will notify the presenter via a callback, and the controller will call the view method view.showUserError(). Callbacks are used not return parameters because of the async nature of hitting our API bac kend.

The Object under test is the Presenter. Specifically, I want to test that the View.showUserError() gets called when an exception occurs in the Api. I believe I can mock Api.checkForUpdates() to immediately call the exception callback instead of doing an actual network call.

The problem is, I only see EasyMock mocking return values. For example:

EasyMock.expect(api.checkForUpdates()).andReturn(xxxx)

wont work for me, since api.checkForUpdates() does not return anything and instead does a callback. What I really want to do is something like:

EasyMock.expect(api.checkForUpdates()).andExecute(exceptionCallback(NetworkError));

But I don't see how to do that. Is there something that can do what I want or am I missing something basic?

Thanks

Upvotes: 1

Views: 5443

Answers (2)

Henri
Henri

Reputation: 5731

EasyMock is a good choice :-) Look at the documentation to get more information.

You can call do andThrow(exceptionCallback(NetworkError) which might suit your needs.

If you need something more powerful, andAnswer will let you do anything you want to create the answer. andDelegateTo might also be a good choice but you will have to implement a class implementing the same interface as the mock. Which will probably be more complex than the two other options in your case.

Upvotes: 1

inza9hi
inza9hi

Reputation: 114

I think you can make a stub using ‘ Expect().andDelegateTo()’ API.

http://devlearnings.wordpress.com/2010/07/10/easymock-assert-arguments-of-method-call/

Upvotes: 2

Related Questions