16

What is the difference between

EasyMock.isA(String.class) 

and

EasyMock.anyObject(String.class)

(Or any other class supplied)

In what situations would would you use one over the other?

emilyk
  • 713
  • 5
  • 14
  • 26

2 Answers2

23

The difference is in checking Nulls. The isA returns false when null but anyObject return true for null also.

import static org.easymock.EasyMock.*;
import org.easymock.EasyMock;
import org.testng.annotations.Test;


public class Tests {


    private IInterface createMock(boolean useIsA) {
        IInterface testInstance = createStrictMock(IInterface.class);
        testInstance.testMethod(
                useIsA ? isA(String.class) : anyObject(String.class)
        );
        expectLastCall();
        replay(testInstance);
        return testInstance;
    }
    private void runTest(boolean isACall, boolean isNull) throws Exception {
        IInterface testInstance = createMock(isACall);
        testInstance.testMethod(isNull ? null : "");
        verify(testInstance);
    }
    @Test
    public void testIsAWithString() throws Exception {
        runTest(true, false);
    }
    @Test
    public void testIsAWithNull() throws Exception {
        runTest(true, true);
    }
    @Test
    public void testAnyObjectWithString() throws Exception {
        runTest(false, true);
    }
    @Test
    public void testAnyObjectWithNull() throws Exception {
        runTest(false, false);
    }

    interface IInterface {
        void testMethod(String parameter);
    }
}

In the example the testIsAWithNull should fail.

terjekid
  • 390
  • 1
  • 11
  • I think you got your runTest methods backwards in the code, but I get what you're saying! Thanks! – emilyk Feb 03 '15 at 23:55
3

I got really confused with Easymock documentation as EasyMock.isA() in API docs is said to return a Class Object on which it is called, but Easymock documentation(for isA(Class clazz)) says that

Matches if the actual value is an instance of the given class, or if it is in instance of a class that extends or implements the given class. Null always return false. Available for objects.

for anyObject() it says

Matches any value.

You can have a look at Documentation here

no specific difference mentioned between these two methods.

Vihar
  • 3,626
  • 2
  • 24
  • 47
  • I looked at that but it still wasn't clear to me. Does this mean that anyObject() matches only an instance of that class and isA() will match an instance of that class and any subclasses? – emilyk Dec 17 '14 at 18:31
  • So then there is no difference? – emilyk Dec 18 '14 at 18:49
  • Actually as per method Naming conventions isA() should be a method returning a boolean, but only god knows why it returns a instance – Vihar Dec 19 '14 at 04:08