[SOLVED] @Component always null in spring boot

In my project, two of my classes have the annotation @Component

@Component
public class ClientMapper {
  public Client convert(ClientEntity clientEntity) {
    Client client = new Client();
    BeanUtils.copyProperties(clientEntity, client);
    return client;
  }

  public ClientEntity convert(Client client) {
    ClientEntity clientEntity = new ClientEntity();
    BeanUtils.copyProperties(client, clientEntity);
    return clientEntity;
  }
}
@Component
public class OrderMapper {
  public Order convert(OrderEntity orderEntity) {
    Order order = new Order();
    BeanUtils.copyProperties(orderEntity, order);
    return order;
  }

  public OrderEntity convert(Order order) {
    OrderEntity orderEntity = new OrderEntity();
    BeanUtils.copyProperties(order, orderEntity);
    return orderEntity;
  }
}

I injected them into different services

@Service
@AllArgsConstructor
public class ClientServiceImpl implements ClientService {

  private final ClientMapper clientMapper;
  private final ClientRepository clientRepository;
@Service
@AllArgsConstructor
public class OrderServiceImpl implements OrderService {

  private final OrderMapper orderMapper;
  private final OrderRepository orderRepository;
  private final OrderNumberRepository orderNumberRepository;

But my mappers are empty at all times. I don’t use the new command to create new objects of them. Everything is OK with my repository interfaces as well, thus my method of injecting comments (@AllArgsContrustor) is effective. A brief note: I used @InjectMocks on my services classes in my test classes. Could it be that this annotation caused my mistake to occur?

@ExtendWith(MockitoExtension.class)
public class OrderServiceTest {
  @Mock
  private OrderRepository orderRepository;
  @InjectMocks
  private OrderServiceImpl orderService;

Solution

Because you are using MockitoExtension, spring won’t produce an OrderMapper component.
if you require actual application. Use the MockitoExtension @Spy annotation.

@ExtendWith(MockitoExtension.class)
public class OrderServiceTest {
  @Mock
  private OrderRepository orderRepository;
  @Spy
  private OrderMapper orderMapper = new OrderMapper(); // Note: new OrderMapper() is optional as you have No Argument Constructor
  @InjectMocks
  private OrderServiceImpl orderService;

Or, for practice, @Mock is always preferable to @Spy when running unit tests.

people found this article helpful. What about you?