Search code examples
javaspringhibernate-mappingmapstruct

Why mapper returns null?


Question: Why mapper returns null ?

Can anybody explain me why my mapper(mapstruct) returns null ? When I implement my own mapper then its ok.

@RunWith(MockitoJUnitRunner.class)
@SpringBootTest
class CouponServiceTestSuite {
    @InjectMocks
    private CouponService couponService;
    @Mock
    private CouponRepository couponRepository;
    @Spy
    private CouponDto couponDto;
    @Spy
    private CouponMapper couponMapper;


    @Test
    public void testMapper() {
        Coupon coupon = createCoupon();
        CouponDto couponDto = couponMapper.mapToCouponDto(coupon);

        System.out.println(couponDto); // RETURN NULL
    }
@Component
@Mapper
public interface CouponMapper {

    Coupon mapToCoupon(CouponDto couponDto);

    CouponDto mapToCouponDto(Coupon coupon);

    default List<CouponDto> mapToCouponDtoList(List<Coupon> couponList) {
        if (couponList == null) {
            return new ArrayList<>();
        }
        return new ArrayList<>(couponList).stream()
                .map(this::mapToCouponDto)
                .collect(Collectors.toList());
    }
}

https://github.com/kenez92/BetWinner2/blob/CouponServiceTestSuite/src/test/java/com/kenez92/betwinner/service/CouponServiceTestSuite.java

Thank you :)


Solution

  • It returns null because you have a @Spy. This means that Mockito will wrap the implementation in an instance of its own and then invoke the methods (if it is null it will return null for the methods).

    You should probably use @SpyBean and @MockBean from Spring Boot if you want to have the beans which are available in your application context spied or mocked.