[英]How to mock MapStruct nested mapper in JUnit5
我一直在尋找大約一天的解決方案。 我仍然無法提供一個工作示例。
我的問題很簡單。 我有一個映射器使用另一個映射器:
@Mapper(componentModel = "spring", uses = {RoleMapper.class})
public interface UserMapper {
/**
* Converts User DTO to User JPA Entity
* @Mapping annotation is used to convert fields with different names
* @param dto
* @return
*/
@Mappings({
@Mapping(target = "identityNo", source = "dto.userIdentity"),
@Mapping(target = "role", source = "dto.roleDTO")
})
User dtoToEntity(UserDTO dto);
/**
* Converts User JPA Entity to User DTO
* @Mapping annotation is used to convert fields with different names
* @param entity
* @return
*/
@Mappings({
@Mapping(target = "userIdentity", source = "entity.identityNo"),
@Mapping(target = "roleDTO", source = "entity.role")
})
UserDTO entityToDto(User entity);
}
@Mapper(componentModel = "spring")
public interface RoleMapper {
Role roleDtoToEntity(RoleDTO dto);
RoleDTO roleEntityToDto(Role entity);
}
我的測試 class 測試映射器正常工作:
class UserMapperTest {
private UserMapper mapper = Mappers.getMapper(UserMapper.class);
@Test
void dtoToEntity() {
User user = new User();
user.setName("john");
user.setSurname("doe");
user.setIdentityNo("11111111111");
user.setRole(new Role("ROLE_ADMIN"));
UserDTO dto = mapper.entityToDto(user);
Assertions.assertEquals(user.getName(), dto.getName());
Assertions.assertEquals(user.getSurname(), dto.getSurname());
Assertions.assertEquals(user.getIdentityNo(), dto.getUserIdentity());
Assertions.assertEquals(user.getRole().getName(), dto.getRoleDTO().getName());
}
}
但是,在自動生成的 impl class UserMapperImpl中調用 roleMapper 的行上會拋出 NullPointerException :
它涉及到我的基本問題,如何模擬或自動連接嵌套映射器 class?
嵌套映射器為 null,因為未加載 Spring 上下文。 因此,@Autowired 不起作用。
解決方案是通過 ReflectionTestUtils 注入嵌套映射器。
@InjectMocks
private UserMapper mapper = UserMapperImpl.INSTANCE;
@Before
public void init() {
RoleMapper roleMapper = Mappers.getMapper(RoleMapper.class);
ReflectionTestUtils.setField(mapper, "roleMapper", roleMapper);
}
我不了解您的應用程序的生態系統,但如果您使用 spring 引導,您可以將測試 class UserMapperTest 標記為@SpringBootTest
並將您的映射器自動裝配為常規 bean
@Autowired
private UserMapper mapper;
正如Jakub Słowikowski提到的,但更花哨:
@ExtendWith(MockitoExtension.class)
class MyClassTest {
@InjectMocks
private MyService myService;
@Mock
private MyApi myApi;
@Spy
private MyMapper myMapper = Mappers.getMapper(MyMapper.class);
@Test
void myTest() {
...
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.