英文:
Why mapper returns null?
问题
为什么 mapper 返回 null?
有人能解释一下为什么我的 mapper(mapstruct)返回 null 吗?当我实现自己的 mapper 时,一切正常。
@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); // 返回 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());
}
}
GitHub 链接:https://github.com/kenez92/BetWinner2/blob/CouponServiceTestSuite/src/test/java/com/kenez92/betwinner/service/CouponServiceTestSuite.java
谢谢
英文:
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());
}
}
Thank you
答案1
得分: 0
它返回null是因为你使用了@Spy
。这意味着Mockito将使用自己的实例包装实现,然后调用方法(如果它为null,则对方法返回null)。
如果你想要对在你的应用程序上下文中可用的bean进行监视或模拟,你可能应该使用Spring Boot的@SpyBean
和@MockBean
。
英文:
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.
答案2
得分: 0
使用 Mappers.getMapper 将解决这个问题,我尝试使用 @SpyBean 和 @MockBean 都没有对我起作用。
英文:
Instead of using
@Spy
private CouponMapper couponMapper;
use-
private final CouponMapper couponMapper= Mappers.getMapper(CouponMapper.class);
using Mappers.getMapper will solve this issue, I tried using @SpyBean and @MockBean did not worked for me.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论