I need to access a Spring bean from a custom mapping method. But I also need to be able to inject a mock of that Spring bean when unit-testing that mapping method.
Here is a minimal example of my mapper class:
@Mapper(componentModel = "spring")
public abstract class MyMapper {
private final MyBean myBean;
public MyMapper(MyBean myBean) {
this.myBean = myBean;
}
@BeforeMapping
protected MyElement initElement(MyElementDto dto) {
// custom logic using the injected MyBean to initialize MyElement
}
public abstract MyElement map(MyElementDto dto);
}
I would expect MapStruct to generate an implementation where it uses MyMapper
's parameterized constructor like so:
@Component
public class MyMapperImpl extends MyMapper {
@Autowired
public MyMapperImpl(MyBean myBean) {
super(myBean);
}
// ... mapping function implementation ...
}
However, MapStruct seems to ignore parameterized constructors and only support default parameter-less constructors.
So the question is: How can I implement this type of logic in the cleanest way so that the generated mapper implementation is unit-testable and it is possible to mock the MyBean
dependency properly?
Using MapStruct 1.3.0.Final, Spring 4.3.25.Release, Mockito 1.9.5 and Junit 4.12.