[英]Is there any way to unit test a Mapstruct with nested Mapper?
我正在嘗試對 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.BeanInstantiationException:無法實例化 [com.mycompany.cna.projects.fishmarket.back.events.repositories.mappers.event.EventMapper]:指定 class 是一個接口
我已經嘗試使用 Mapper.getMapper(EventMapper.class) 實例化映射器,它返回了 NullPointerException。
我應該怎么做才能對這些映射器進行單元測試?
我已經解決了這個問題。 問題是我沒有實例化我的 Mocks object。 我還在 before 方法中為 EventMapperImpl 提供了嵌套映射器的模擬:
@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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.