The first time I heard the name mockito, I thought it was such a cute name to be an open source testing framework for Java. However, during my Java learning process I have learned to appreciate what mockito can do for me and how important is to understand it, specially if I have to work using TDD.
The JUnit testing framework, makes the testing of an independent, non-void method simple. But how do we test a method with no return value? How do we test a method that interacts with other domain objects?. Well here is when mockito is useful.
Here are basic concepts of this framework that hope it helps to anyone who is new with it:
What is it?
It’s a framework that allows the creation of test double objects (mock objects) in automated unit tests for the purpose of Test-driven Development (TDD) or Behavior Driven Development (BDD).
A mock object is an objet that:
Is created by the mock framework
Implements the same interface as the original dependent object. Otherwise, the compiler won’t let us pass it to the tested object.
Supplies the tested code with everything it expects from the dependent object.
Allows us to check that the tested code is using the dependent object (the Mock) correctly
Why Mockito?
Use mockito to get smart “fake” implementation of classes or interfaces out of your reach (p.s. My rule of thumb is to use mockito to mock all “other” classes that are being touch when testing a class )
What we should do to use a Mock Object?
- Create instance of the Mock
- Define behavior during test
- Invoke the tested code while passing the Mock as parameter
- Verify the Mock has been used correctly
How to create mock objects?
ClassToMock mockObject = mock(ClassToMock.class);
Mockito.mock(ClassToMock.class);
or
@Mock
ClassToMock mockObjectl
@Before
public void setUp(){
MockitoAnnotations.initMocks(this);
}
How to verify Invocation on Mocks?
//simple “equals”
verify(properties).get(“property”);
//matchers
verify(properties).get(eq(“property”));
What does when(…) and then (…) means?
when(methodIsCalled).thenReturn(aValue);
when(methodIsCalled).thenThrown(anException);
Example of a classical test in JUnit:
@Test
public void test(){
UnitToTest testee = new UnitToTest();
Helper helper = new Helper();
testee.doSomething(helper);
assertTrue(helper.somethingHappened());
}
Example of test using mockito:
@Test
public void test(){
Helper myMock = mock(Helper.class);
when(myMock.isCalled()).thenReturn(true);
testee.doSomething(myMock);
verify(myMock).isCalled();
}
Real Code Example:
Properties properties = mock(Properties.class);
when(properties.get(“shoeSize”).thenReturn(“42”);
String result = properties.get(shoeSize");
assertEquals(“42”, result);
//optional:
verify(properties).get(“shoeSize”);