Search code examples
javamockingeasymock

EasyMock mock same method with different parameters


This question is similar to this one but for EasyMock instead of Mockito.

I have some test code like this.

expect(mockObject.someMethod("some input", ReturnClassOne.class)).andReturn(returnObjectOne);
expect(mockObject.someMethod("some different input", ReturnClassTwo.class)).andReturn(returnObjectTwo);

But this leads to the second line throwing the following exception.

java.lang.IllegalStateException: last method called on mock already has a non-fixed count set.

How can I mock mockObject.someMethod to accept two calls with different input params?


Solution

  • This should perfectly work. EasyMock supports these two recording and will differentiate. For instance, the code below works fine.

    So you case is specific. Maybe the someMethod signature has something special. I would be interested in having a full test case.

    public class MyTest {
    
        public static class ReturnClassOne {}
        public static class ReturnClassTwo {}
    
        public static class MyClass {
    
            public <T> T someMethod(String s, Class<T> c) {
                try {
                    return c.newInstance();
                } catch (InstantiationException | IllegalAccessException e) {
                    throw new RuntimeException(e);
                }
            }
    
        }
    
        @Test
        public void test() {
            MyClass mockObject = mock(MyClass.class);
            expect(mockObject.someMethod("some input", ReturnClassOne.class)).andReturn(new ReturnClassOne());
            expect(mockObject.someMethod("some different input", ReturnClassTwo.class)).andReturn(new ReturnClassTwo());
            replay(mockObject);
            mockObject.someMethod("some input", ReturnClassOne.class);
            mockObject.someMethod("some different input", ReturnClassTwo.class);
            verify(mockObject);
        }
    }