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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With