¿Puedo probar el código que usa la introspección con Mockito?

I'm writing unit tests for a block of code that uses introspection; specifically it calls getDeclaredField() on the class I want to mock and tries to get the value of the field. Is there a way to mock this with Mockito?

preguntado el 25 de abril de 13 a las 00:04

1 Respuestas

Mockito operates using the same introspection libraries you're trying to fool by creating a Mock. Even if you could cajole it to work, I'm not sure how easy it would be to understand or maintain.

I'd suggest creating a very small nested class and operating on it normally:

public class YourTest {
  private static class SampleClass {
    String field1;
    int field2;
  }

  @Test public void introspectionWorks() {
    yourSUT.process(new SampleClass());
  }
}

Barring that, extract the difficult-to-mock call into a method you can stub easily:

public class YourSUT {
  /* ... */

  /* package */ Class<?> getFieldType(Object object, String fieldName) {
    return object.getClass().getDeclaredField(fieldName).getType();
  }
}

public class YourTest {
  @Test public void introspectionWorks() {
    YourSUT spy = Mockito.spy(yourSUT);
    doReturn(String.class).when(spy).getFieldType(myObject, "someStringField");
  }
}

Respondido 27 Abr '13, 04:04

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.