Easymock: matcher calls were used outside expectations

15k views Asked by At

I changed the return value of a method in my code from void to and Object. Then two junit test failed stating that an expect(...).andReturn(...) was missing. After adding those one test is fixed and the other still throws an exception which seems a bit weird:

java.lang.IllegalStateException: matcher calls were used outside expectations

The code which works for one but not the other is:

expect(myMock.foo(1l,FooEnum.A)).andReturn(EasyMock.anyObject(String.class));

Any ideas?

3

There are 3 answers

0
Lonzak On BEST ANSWER

I changed to code to

expect(myMock.foo(1l,FooEnum.A)).andReturn(new Object());

and now it works. It's still strange why I get this error since I definitely return a new Object (and not null or anything)

2
Karrde On

EasyMock.anyObject(String.class) is a matcher, it isn't a String and can't be used as a String except for matching - matching being something like the following:

when(foo.bar(EasyMock.anyObject(String.class))).thenReturn("foo-bar")

P.S. you should avoid using new String() whenever possible; it's always better to use "" instead.

0
Nick On

I was having this same problem with an AmazonSQSClient object. I tried .andReturn(new Object()), but got an incompatible type error. To fix this, simply return a new object of the type the method expects:

expect(amazonSQSClient.getQueueAttributes(queueUrl, attributeNames)).andReturn(new GetQueueAttributesResult());