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?
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.