mockito
Mockito Best Practices
Ricerca…
Stile BDDMockito
Lo stile di testing Behavior Driven Development (BDD) ruota attorno alle fasi "date", "when" e "then" nei test. Tuttavia, il classico Mockito usa la parola "quando" per la fase "data" e non include altre costruzioni del linguaggio naturale che possono comprendere BDD. Pertanto, gli alias BDDMockito sono stati introdotti nella versione 1.8.0 al fine di facilitare i test guidati dal comportamento.
La situazione più comune è quella di stub restituire un metodo. Nell'esempio seguente, il getStudent(String)
dello StudentRepository
deriso restituirà un new Student(givenName, givenScore)
se invocato con un argomento uguale a givenName
.
import static org.mockito.BDDMockito.*;
public class ScoreServiceTest {
private StudentRepository studentRepository = mock(StudentRepository.class);
private ScoreService objectUnderTest = new ScoreService(studentRepository);
@Test
public void shouldCalculateAndReturnScore() throws Exception {
//given
String givenName = "Johnny";
int givenScore = 10;
given(studentRepository.getStudent(givenName))
.willReturn(new Student(givenName, givenScore));
//when
String actualScore = objectUnderTest.calculateStudentScore(givenName);
//then
assertEquals(givenScore, actualScore);
}
}
A volte si desidera verificare se l'eccezione generata dalla dipendenza viene gestita o riscritta correttamente in un metodo sotto test. Tale comportamento può essere soppresso nella fase "data" in questo modo:
willThrow(new RuntimeException())).given(mock).getData();
A volte si desidera impostare alcuni effetti collaterali che un metodo di prova dovrebbe introdurre. Soprattutto può tornare utile quando:
il metodo stub è un metodo che dovrebbe modificare lo stato interno di un oggetto passato
il metodo stubico è un metodo vuoto
Tale comportamento può essere soppresso nella fase "data" con una "risposta":
willAnswer(invocation -> this.prepareData(invocation.getArguments()[0])).given(mock).processData();
Quando si desidera verificare le interazioni con una simulazione, può essere eseguita nella fase "then" con i metodi should()
o should(VerificationMode)
(solo da 1.10.5):
then(mock).should().getData(); // verifies that getData() was called once
then(mock).should(times(2)).processData(); // verifies that processData() was called twice
Quando si desidera verificare che non ci siano più interazioni con una simulazione oltre a quelle già verificate, è possibile farlo nella fase "then" con shouldHaveNoMoreInteractions()
(dalla 2.0.0):
then(mock).shouldHaveNoMoreInteractions(); // analogue of verifyNoMoreInteractions(mock) in classical Mockito
Quando si desidera verificare che non ci siano assolutamente interazioni con una simulazione, è possibile farlo nella fase "then" con shouldHaveNoMoreInteractions()
(dalla 2.0.0):
then(mock).shouldHaveZeroInteractions(); // analogue of verifyZeroInteractions(mock) in classical Mockito
Quando si desidera controllare se i metodi sono stati richiamati in ordine può essere fatto nella fase "then" con should(InOrder)
(dal 1.10.5) e should(InOrder, VerificationMode)
(dalla 2.0.0):
InOrder inOrder = inOrder(mock);
// test body here
then(mock).should(inOrder).getData(); // the first invocation on the mock should be getData() invocation
then(mock).should(inOrder, times(2)).processData(); // the second and third invocations on the mock should be processData() invocations