Mockito is a mocking framework used to better isolate tests by using mock objects (dummy implementations).
Here is how to create a mock object:
Node node = Mockito.mock(Node.class);
You can also create mock objects with the annotations @RunWith and @Mock:
@RunWith(MockitoJUnitRunner.class) public class MyClass { @Mock private Node node; // Other code }
Or you can use the annotation @Mock alone:
public class MyClass { @Mock private Node node; public MyClass() { MockitoAnnotations.initMocks(this); } // Other code }
Use @InjectMocks insead of @Mock if you also want to execute the constructor or inject by either constructor, setter or property:
@InjectMocks Node node;
On a mock object you can do different things. You can set a return value for a particular method:
Mockito.when(mockObject.myMethod()).thenReturn(49);
You can do the same, but without actually executing the method:
Mockito.doReturn(49).when(myMock).MyMethod();
If your method accepts a parameter, you can return a specific result only for a specific input:
Mockito.doReturn(49).when(myMock).MySquareMethod(7);
You can verify a method has been called:
Mockito.verify(myMock).myMethod(Matchers.eq(5));
You can verify the number of calls to a method:
Mockito.verify(myMock, Mockito.times(3));
You can use the annotation @Spy to wrap a real object and add some control over it:
@Spy private Node node = new Node();
Or:
Node node = spy(new Node());
Copyright © 2013 Welcome to the website of Davis Fiore. All Rights Reserved.