本文介绍了Easymock isA与anyObject的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



What is the difference between

EasyMock.isA(String.class)

EasyMock.anyObject(String.class)

(或提供的任何其他类)

(Or any other class supplied)

在什么情况下,您会使用另一个?

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

推荐答案

区别在于检查Null。当为null时,isA返回false,但对null而言,anyObject返回true。

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);
    }
}

在该示例中,testIsAWithNull应该失败。

In the example the testIsAWithNull should fail.

这篇关于Easymock isA与anyObject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 20:33