Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easymock isA vs anyObject

Tags:

easymock

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?

like image 738
emilyk Avatar asked Dec 16 '14 22:12

emilyk


2 Answers

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.

like image 153
terjekid Avatar answered Oct 17 '22 15:10

terjekid


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

  • http://easymock.org/user-guide.html#verification-expectations

no specific difference mentioned between these two methods.

like image 34
Vihar Avatar answered Oct 17 '22 16:10

Vihar