Making layout with Jmock to return null for yourself
I have a method that looks something like this:
public void myMethod(MyClass c)
{
if (c == null)
{
return;
}
try
{
c.someMethod();
}
catch (SomeException e)
{
// log the exception, possibly re-throw
}
}
I'm trying to find a way to set a mock instance of the MyClass parameter c such that it returns null for itself and that c.someMethod () is never called. My unit test looks like this:
@Test
public void Test_myMethod_With_Null_MyClass_Does_Not_Call_someMethod()
{
Mockery mockery = new Mockery()
{{
setImposteriser(ClassImposteriser.INSTANCE);
}};
final MyClass mockMyClass = mockery.mock(MyClass.class);
try
{
mockery.checking(new Expectations()
{{
oneOf(mockMyClass).equals(null);
will(returnValue(true));
never(mockMyClass).someMethod();
}});
}
catch (Exception e)
{
logger.fatal(e);
fail("Exception thrown in test.");
}
Util.myMethod(mockMyClass);
}
Basically, I create a mock instance of MyClass and set expectations on it that when its value is checked for null it will return true and that the someMethod () method is never called.
At the moment the test is failing because jMock says it is not possible to override the methods provided by the Object class (equal (null) part).
Is there a way to do this using jMock? Does this pattern make sense? Is this a valid test? If not, does anyone have any suggestions for testing this?
a source to share
I don't think you can test this code using JMock alone.
I would check this by passing directly null
. If no exceptions are thrown or logged, you know that your code worked as expected. @Test
public void Test_myMethod_With_Null_MyClass_Does_Not_Call_someMethod()
{
Util.myMethod(null);
//no exception should be thrown.
}
If you want to make it more explicit, you can wrap the call myMethod(null)
in a try / catch block, but this is optional, other than to clarify the reason for the failure.
public void Test_myMethod_With_Null_MyClass_Does_Not_Call_someMethod()
{
try
{
Util.myMethod(null);
}
catch( ExpectedException e )
{
fail( "Should not have thrown exception: " + e.getMessage() );
}
}
This is a sufficient test, because you know that if c
there is null
, then of c.something()
course it cannot be called.
a source to share