[在某些映射器类中,我需要使用自动连接的ObjectMapper来将String
转换为JsonNode
或反之。通过使用@autowired
的场注入,可以实现我的目标。但这不适合单元测试,因此我想尝试使用构造函数注入。
我当前使用字段注入的工作代码:
@Mapper(componentModel = "spring")
public class CustomMapper {
@autowired
ObjectMapper mapper;
}
我尝试将其转换为构造函数注入,以便可以在单元测试中提供构造函数参数:
@Mapper(componentModel = "spring")
public class CustomMapper {
ObjectMapper mapper;
public CustomMapper(ObjectMapper mapper) {
this.mapper = mapper;
}
}
但是在编译过程中出现Constructor in CustomMapper cannot be applied to the given type
错误。我如何解决它?还是在Mapstruct中还有其他更好的方法将String
映射到JsonNode
?
构造函数注入不能在映射器定义中使用。仅在映射器实现中。
但是,对于单元测试,我建议您使用二传手进样。
您的映射器将如下所示:
@Mapper( componentModel = "spring")
public class CustomMapper {
protected ObjectMapper mapper;
@Autowired
public void setMapper(ObjectMapper mapper) {
this.mapper = mapper;
}
}
您可以这样操作:
@Mapper(componentModel = "spring")
@RequiredArgsConstructor //lombok annotation, which authowire your field via constructor
public class CustomMapper {
private final ObjectMapper mapper;
}
但是您仍然可以通过字段来完成。在两种情况下,您都应该在测试中模拟它。只要记住使用@InjectMocks
public CustomMapperTest {
@InjectMocks
private CustomMapper customMapper;
@Mock
private ObjectMapper objectMapper
@BeforeEach
void setUp() {
customMapper= new CustomMapperImpl();
MockitoAnnotations.initMocks(this);
when(objectMapper.map()).thenReturn(object);
}
@Test
void shouldMap() {
Object toObject = customerMapper.map(fromObject);
}
}