Tengo debajo de la configuración de las clases.
class Base { @Autowired private BaseService service; //No getters & setters .... } @Component class Child extends Base { private final SomeOtherService otherService; @Autowired Child(SomeOtherService otherService) { this.otherService = otherService; } } Estoy escribiendo una prueba de unidad para la clase Child . Si uso @InjectMocks , el otherService resulta ser nulo. Si uso, el constructor de la clase Child en la configuración de la prueba, entonces los campos en la clase Base resultan ser null .
Conozco todos los argumentos acerca de que la inyección de campo es mala, pero estoy más interesado en saber si hay una manera de resolver esto sin cambiar la forma en que las clases Base y Child inyectan sus propiedades.
¡¡Gracias!!
Solo haz esto:
public class Test { // Create a mock early on, so we can use it for the constructor: OtherService otherService = Mockito.mock(OtherService.class); // A mock for base service, mockito can create this: @Mock BaseService baseService; // Create the Child class ourselves with the mock, and // the combination of @InjectMocks and @Spy tells mockito to // inject the result, but not create it itself. @InjectMocks @Spy Child child = new Child(otherService); @Before public void before() { MockitoAnnotations.initMocks(this); } }Mockito debería hacer lo correcto.