我正在尝试对Mapstruct嵌套映射器进行单元测试,如下所示:
@Mapper(componentModel = "spring", uses = EventCategoryMapper.class, injectionStrategy = InjectionStrategy.CONSTRUCTOR)
public interface EventMapper {
Event fromEventMO(EventMO eventMO);
EventMO toEventMO(Event event);
default Optional<Event> fromOptionalEventMO(Optional<EventMO> optionalEventMO) {
return (optionalEventMO.isEmpty()) ? Optional.empty() : Optional.of(fromEventMO(optionalEventMO.get()));
}
}
@Mapper(componentModel = "spring", injectionStrategy = InjectionStrategy.CONSTRUCTOR)
public interface EventCategoryMapper {
EventCategory fromEventCategoryMO(EventCategoryMO eventCategoryMO);
EventCategoryMO toEventCategoryMO(EventCategory eventCategory);
default String fromPriorityMO(PriorityMO priority) {
return (priority.getPriority()==null) ? null : priority.getPriority();
}
我正在尝试测试EventMapper:
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = {EventMapper.class, EventCategoryMapper.class, EventMapperImpl.class, EventCategoryMapperImpl.class})
public class EventMapperTest {
private Mocks mocks; //This object contains the mocked objects that should be mapped.
@Autowired
private EventMapper eventMapper;
@Test
@DisplayName("Should return an Event from an EventMO")
void shouldReturnEventfromEventMO() {
var event = eventMapper.fromEventMO(mocks.getEventMO());
assertEquals(event.getId(), 123L);
}
但它不断失败:
创建名为"eventMapper"的bean时出错:bean的实例化失败;嵌套异常为org.springframework.beans.BeanInstanceException:未能实例化[mycompany.cna.projects.fishmarket.back.events.repositions.mappers.event.EventMapper]:指定的类是接口
我已经尝试用mapper.getMapper(EventMapper.class(实例化映射器,它返回了一个NullPointerException。
我应该怎么做才能在这些类型的映射器上实现单元测试?
我已经解决了这个问题。问题是我没有实例化Mocks对象。我还在前面的方法中为EventMapperImpl提供了一个嵌套映射器的mock:
@ExtendWith(SpringExtension.class)
public class EventMapperTest {
private Mocks mocks;
private EventMapper eventMapper;
@Mock
private EventCategoryMapper eventCategoryMapper;
@BeforeEach
void before() {
eventMapper = new EventMapperImpl(eventCategoryMapper);
mocks = new Mocks();
}
@Test
@DisplayName("Should return an Event from an EventMO")
void shouldReturnEventfromEventMO() {
when(eventCategoryMapper.fromEventCategoryMO(any(EventCategoryMO.class))).thenReturn(mocks.getEventCategory());
var event = eventMapper.fromEventMO(mocks.getEventMO());
assertEquals(event.getId(), 123L);
}