0

I'm having a problem. I have an abstract class to which I inject its dependencies. They all build fine except for Jackson ObjectMapper.

Abstract class:

protected final ObjectMapper objectMapper;

private final String apiName;

@Autowired private MeliRestClient restClient;

public AbstractClientRepository(String apiName) {
  this.apiName = apiName;
  objectMapper = new ObjectMapper();
  objectMapper.registerModule(new JavaTimeModule());
}

Test class:

  @Mock
  private MeliRestClient restClient;

  @Mock
  private MeliRequestBuilder requestBuilderMock;

  @Mock
  private ObjectMapper objectMapper;

  @InjectMocks
  private static AbstractClientRepository abstractClientRepository;

  private static final String poolName = "pool";

  @BeforeAll
    public static void setUp() throws RestException {
    RoutingHelper.setMeliContext(MeliContextBuilder.build(Collections.emptyMap()));
    abstractClientRepository = Mockito.mock(
      AbstractClientRepository.class,
      Mockito.CALLS_REAL_METHODS);
  }

Resultado: Clase de test

As you can see, the restClient is mocked and injected correctly, but the ObjectMapper is not. Any help?

Thank you!

ZottoSL
  • 170
  • 1
  • 12
  • 3
    You are mocking an object. The mock object doesn't call actual code. So constructor is not called. Due to that the objects are not initialized. Instead of mocking, create the real object and assign mock objects to it. – Dhaval Gajjar Apr 21 '23 at 13:02
  • The class is abstract, I can't create a object from it. – ZottoSL Apr 21 '23 at 14:58
  • You only mocked the field in the test class, not the one in the AbstractClientRepository. (The latter is not possible without code changes). – Hulk Apr 21 '23 at 15:38
  • Does this answer your question? [How to test abstract class in Java with JUnit?](https://stackoverflow.com/questions/7569444/how-to-test-abstract-class-in-java-with-junit) – Hulk Apr 21 '23 at 15:40
  • Does this answer your question? [Why are my mocked methods not called when executing a unit test?](https://stackoverflow.com/questions/74027324/why-are-my-mocked-methods-not-called-when-executing-a-unit-test) – knittl Jun 02 '23 at 09:45

0 Answers0