Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

206
Views
Primavera: prueba unitaria para la clase que tiene inyección de campo y constructor

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!!

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!