Ho il seguente test in cui ho bisogno di verificare che tutti i getter della classe Person vengano chiamati. Finora ho usato mockito's verify() per assicurarmi che ogni getter venga chiamato. C'è un modo per farlo con la riflessione? Può succedere che un nuovo getter venga aggiunto alla classe Person ma il test mancherà questo.Verificare che tutti i metodi getter siano chiamati
public class GetterTest {
class Person{
private String firstname;
private String lastname;
public String getFirstname() {
return firstname;
}
public String getLastname() {
return lastname;
}
}
@Test
public void testAllGettersCalled() throws IntrospectionException{
Person personMock = mock(Person.class);
personMock.getFirstname();
personMock.getLastname();
for(PropertyDescriptor property : Introspector.getBeanInfo(Person.class).getPropertyDescriptors()) {
verify(personMock, atLeast(1)).getFirstname();
//**How to verify against any getter method and not just getFirstName()???**
}
}
}
Great! Per quanto riguarda il tuo ultimo consiglio, penso che il test non sia per Person ma per qualche classe come PersonBuilder, PersonCloner o qualcosa di simile – Raffaele
@Raffaele: Vero, ma si spera che la soluzione migliore sia controllare effettivamente che ogni campo sia copiato, il che implica (ma non non richiedere) che ogni getter è stato chiamato. –
Questo ha funzionato con il minimo sforzo per verificare la chiamata di tutti i metodi getter. Alcune modifiche però: 'BeanInfo beanInfo = Introspector.getBeanInfo (Person.class);' e aggiunto per 'setOfDescriptors' un filtro con:' .filter (p ->! P.contains ("getClass")) 'in modo che questo metodo non è preso in considerazione. –