Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set negative expectations in EasyMock

Tags:

easymock

I would like to understand EasyMock better, and working with it I came up with this question.

What I would like to do is setting up a negative expectation over an object, to check if a certain method is not called during the test (when verifying those initial expectations).

I know that the default behaviour of verify is checking both cases: your expectations were met, and no other calls were performed; but there is no record in the test that a certain method is not called, in other words, if you set an expectation over this method and it doesn't get called, your test will fail (confirming that your implementation is behaving properly!).

Is there a way using EasyMock to set this up? I couldn't find anything in the documentation.

Thank you for your attention, and in advance for your help!

like image 605
Javi Carretero Avatar asked Feb 15 '12 12:02

Javi Carretero


People also ask

Which of the given method is used to create EasyMock?

The expect() method tells EasyMock to simulate a method with certain arguments. The andReturn() method defines the return value of this method for the specified method parameters. The times() method defines how often the Mock object will be called. The replay() method is called to make the Mock object available.

How do you expect a void method to call in EasyMock?

andVoid() If we just want to mock void method and don't want to perform any logic, we can simply use expectLastCall(). andVoid() right after calling void method on mocked object. You can checkout complete project and more EasyMock examples from our GitHub Repository.

What does EasyMock verify do?

EasyMock can ensure whether a mock is being used or not. It is done using the verify() method.


1 Answers

The way EasyMock works is like this:

  1. create a Mock Object for the interface you would like to simulate,
  2. record the expected behavior, and
  3. switch the Mock Object to replay state.

Like in following if you don't set any expectation:

mock = createMock(YourInterface.class); // 1
// 2 (we do not expect anything)
replay(mock); // 3

then it means that if ClassUnderTest call any of the interface's methods, the Mock Object will throw an AssertionError like this:

java.lang.AssertionError: 
  Unexpected method call yourMethodWhichYouDidNotExpectToBeCalled():

This itself is Negative Expectation checking.

like image 200
Kuldeep Jain Avatar answered Nov 16 '22 06:11

Kuldeep Jain