Mockito is a very useful unit test
framework and it has now become vastly famous in java software developers
community. Few advantages of Mockito from its predecessors is that
Mockito can create mock objects of concrete classes (earlier unit test frameworks
only could mock interfaces) and it is very simple and understandable.
This article only highlights few useful techniques that are used when using Mockito and is only for the readers who already has experience in Mockito. But for beginners, there are many small tutorials available on the web to get things going.
Mock a method using Mockito
ConcreteClass mockObject =
ConcreteMockito.mock(ConcreteClass.class)
Mockito.when(mockObject.testMethod()).thenReturn(testObject);
Check whether a given method is invoked
In the following code we check whether
testMethod() is called once.
Mockito.verify(concreteClass,
Mockito.times(1)).testMethod();
Check whether an exception is thrown
In following
code the test will fail if testMethod() does not throw an exception.
try
{
instance.testMethod();
fail();
}
catch(SpiderException
)
{
assertTrue(expectedMessage.equals(ex.information));
}
Mock to return the same argument that passed into the method
In the following method the testMethod() is mocked in a way that it returns the same String array which was passed to it as a parameter.
Mockito.when(instance.testMethod(Mockito.any(String[].class)))
.thenAnswer(new Answer<String[]>()
{
public String[] answer(InvocationOnMock
invocation) throws Throwable {
Object[]
args = invocation.getArguments();
return (String[])
args[0];
}
});
No comments:
Post a Comment