Mockito
Diferentes dubls:
Verificar comunicao (Interaes)
Stub (when-thenReturn)
Runtime Exceptions
Verifica Exceptions
Usa matchers (Hamcrest)
Nmero de invocaes
Ordem de chamada
verifica chamada
Ordem de chamada
Inline
Callbacks
Verificar o comportamento
import static [Link].*;
import [Link];
public class AvaliaMockito {
public void avalia_Mockito() {
// criao do mock
List mockedList = mock([Link]);
// solicitando o objeto falso
[Link]("Produto1");
[Link]();
// verificando se foi usado
// retorna true ou false dependendo do uso e parmetros
verify(mockedList).add("Produto1");
verify(mockedList).clear();
}
}
Stub (when-thenReturn)
Runtime Exceptions
public static void avalia_Mockito() {
//You can mock concrete classes, not only interfaces
LinkedList mockedList = mock([Link]);
doThrow(new RuntimeException()).when(mockedList).
clear();
//following throws RuntimeException:
[Link]();
}
Verifica uso de Exceptions
public static void avalia_Mockito() {
//You can mock concrete classes, not only interfaces
LinkedList mockedList = mock([Link]);
//stubbing
when([Link](0)).thenReturn("first");
when([Link](1)).thenThrow(new RuntimeException());
//following prints "first"
[Link]([Link](0));
//following throws runtime exception
try { [Link]([Link](1));
} catch (Exception e) {}
//following prints "null" because get(999) was not stubbed
[Link]([Link](999));
//it is possible to verify a stub, usually it's just redundant
verify(mockedList).get(0); }
Usa matchers (Hamcrest)
public static void avalia_Mockito() {
//You can mock concrete classes, not only interfaces
LinkedList mockedList = mock([Link]);
//stubbing using built-in anyInt() argument matcher
when([Link](anyInt())).thenReturn("element");
//stubbing using hamcrest (let's say isValid() returns your own hamcrest
matcher):
when([Link](argThat(isValid()))).thenReturn(false);
//following prints "element"
[Link]([Link](999));
//you can also verify using an argument matcher
verify(mockedList).get(anyInt()); }
Nmero de invocaes
public static void avalia_Mockito() {
//You can mock concrete classes, not only interfaces
LinkedList mockedList = mock([Link]);
//using mock
[Link]("once");
[Link]("twice");
[Link]("twice");
[Link]("three times");
[Link]("three times");
[Link]("three times");
//following two verifications work exactly the same - times(1) is used by default
verify(mockedList).add("once");
verify(mockedList, times(1)).add("once");
//exact number of invocations verification
verify(mockedList, times(2)).add("twice");
verify(mockedList, times(3)).add("three times");
//verification using never(). never() is an alias to times(0)
verify(mockedList, never()).add("never happened");
//verification using atLeast()/atMost()
verify(mockedList, atLeastOnce()).add("three times");
verify(mockedList, atLeast(2)).add("five times");
verify(mockedList, atMost(5)).add("three times");
}
Ordem de chamada
public static void avalia_Mockito() {
// A. Single mock whose methods must be invoked in a particular order
List singleMock = mock([Link]);
//using a single mock
[Link]("was added first");
[Link]("was added second");
//create an inOrder verifier for a single mock
InOrder inOrder = inOrder(singleMock);
//following will make sure that add is first called with "was added first, then with "was added second"
[Link](singleMock).add("was added first");
[Link](singleMock).add("was added second");
// B. Multiple mocks that must be used in a particular order
List firstMock = mock([Link]);
List secondMock = mock([Link]);
//using mocks
[Link]("was called first");
[Link]("was called second");
//create inOrder object passing any mocks that need to be verified in order
InOrder inOrder2 = inOrder(firstMock, secondMock);
//following will make sure that firstMock was called before secondMock
[Link](firstMock).add("was called first");
[Link](secondMock).add("was called second");
}
Verificando as chamadas
public static void avalia_Mockito() {
List mockOne = mock([Link]);
List mock2 = mock([Link]);
List mock3 = mock([Link]);
//using mocks - only mockOne is interacted
[Link]("one");
//ordinary verification
verify(mockOne).add("one");
//verify that method was never called on a mock
verify(mockOne, never()).add("two");
//verify that other mocks were not interacted
verifyZeroInteractions(mock2, mock3);
}
Anotaes
public class ArticleManagerTest extends SampleBaseTestCase {
@Mock private ArticleCalculator calculator;
@Mock private ArticleDatabase database;
@Mock private UserProvider userProvider;
private ArticleManager manager;
@Before public void setup() {
manager = new ArticleManager(userProvider, database, calculator);
}
}
public class SampleBaseTestCase {
@Before public void initMocks() {
[Link](this);
}
}
Inline (consecutivos)
public static void avalia_Mockito() {
ObjetoTeste mock = mock([Link]);
when([Link]("some arg"))
.thenThrow(new RuntimeException())
.thenReturn("foo"); // ou (one, two, three);
//First call: throws runtime exception:
[Link]("some arg");
//Second call: prints "foo"
[Link]([Link]("some arg"));
//Any consecutive call: prints "foo" as well (last stubbing wins).
[Link]([Link]("some arg"));
}
Callback
public static void avalia_Mockito() {
ObjetoTeste mock = mock([Link]);
when([Link](anyString())).thenAnswer(new Answer()
{
public Object answer(InvocationOnMock invocation) {
Object[] args = [Link]();
Object mock = [Link]();
return "called with arguments: " + args;
}
});
//Following prints "called with arguments: foo"
[Link]([Link]("foo"));
}
Referncias
Mockito - [Link]