Easymock isA vs anyObject

蹲街弑〆低调 提交于 2019-12-08 15:49:56

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/27515157/easymock-isa-vs-anyobject

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!