mercredi 28 septembre 2016

get field value of mocked object by reflection

class Person { 
    private String firstName;
    private String lastName;
    // getters and setters for firstName, lastName
}

@Test
void test() {
    Person p = mock(Person.class);
    when(p.getFirstName()).thenReturn("John");
    when(p.getLastName()).thenReturn("Peter");

    Map<String, Object> someContainerLikeMap = new HashMap<>();

    org.springframework.util.ReflectionUtils.doWithFields(p.getClass(), field -> {
        someContainerLikeMap.put(field.getName(), field.get(p));
        // field.get(p) above, always get null
    }
}

I've got two questions:

  1. get by field reflection, field.get(p), always get null;

  2. iteration of fields, what's the best way to just have fields defined in class Person included, that is, firstName, lastName?





Aucun commentaire:

Enregistrer un commentaire