2 matchers expected, 1 recorded.

In Uncategorized on 15/07/2010 by weirdfellow Tagged: , , , ,

EasyMock is really a nice framework for mocking interfaces, so you can reliably test your classes.

As always – everything is fine, unless you need to do something more complex. As long as you know all parameters passed to the mocks, there are no problems. But sometimes it is not possible to predict all arguments the mock will receive. A bit of research and here it is:

  MyData myData = EasyMock.createNiceMock( MyData.class );
  MyService serviceMock = EasyMock.createMock( MyService.class );

  expect( serviceMock.doSth( EasyMock.<File>anyObject(), myData ).andReturn( true );

Seems OK – doesn’t it? The code tells serviceMock to expects a call to doSth method. The second argument should be myData object, while we don’t care about the first one.

Unfortunately, you will get something like that:

java.lang.IllegalStateException: 2 matchers expected, 1 recorded.
	at org.easymock.internal.ExpectedInvocation.createMissingMatchers(
	at org.easymock.internal.ExpectedInvocation.(
	at org.easymock.internal.ExpectedInvocation.(
	at org.easymock.internal.RecordState.invoke(
	at org.easymock.internal.MockInvocationHandler.invoke(
	at org.easymock.internal.ObjectMethodsFilter.invoke(
	at org.easymock.classextension.internal.ClassProxyFactory$MockMethodInterceptor.intercept(

Unfortunately, it is not possible to mix values and matchers – a anyObject method is a matcher. To make the test execute correctly, all parameters should use matchers instead of just values. Solution is pretty straight forward – use eq matcher:

  expect( serviceMock.doSth( EasyMock.<File>anyObject(), EasyMock.eq( myData ) ).andReturn( true );

In addition to eq matcher, EasyMock does publish a handful of other matchers. Worth noting are aryEq for comparing the array contents and isA for checking the class of given object. The EasyMock site gives a full list of those.


9 Responses to “2 matchers expected, 1 recorded.”

  1. Igor, Have you tried at Mockito. Its great!

  2. Thanks Derek – in new projects I am almost exclusively using Mockito 🙂

  3. that saves me hours…thank you for this article!

  4. Thank you so much for this simplest explanation..Please keep up the good work

  5. Thanks.. It solved my problem.

  6. Tanks!

  7. Thanks … You saved my hours …

  8. Thanks a lot..Worked like magic.

  9. this really helped

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: