MapStruct не работает с Spring-boot Gradle Junit5 - PullRequest
1 голос
/ 28 мая 2019

Я пытаюсь использовать mapstruct с Gradle, но у меня ограниченный успех. Когда я использую его в приложении, кажется, что все работает нормально, но когда я пытался написать некоторые тесты, Spring не может правильно подключить MapStruct (он просто возвращает исключения NullPointer). Я использую Gradle 5.4.1, Junit5 и IntelliJ 2019.1.2.

Это папка сборки, и для тестовых классов нет созданного преобразователя.

введите описание изображения здесь

Репозиторий с кодом находится здесь: https://github.com/MirkoManojlovic/mapstruct-example

Mapper:

@Mapper(unmappedTargetPolicy = ReportingPolicy.WARN,
        componentModel = "spring",
        injectionStrategy = InjectionStrategy.CONSTRUCTOR)
public interface ItemMapper {
    ItemDto toDto(Item item);
    Item toItem(ItemDto itemDto);
}

Repository:

public class ItemRepository {
    public ItemDto getItemDto() {
        return new ItemDto("item 1");
    }

    public Item getItem() {
        return new Item(1, "item 1", 20);
    }
}

Услуги:

@Service
@RequiredArgsConstructor
@Log4j2
public class ItemService {
    private final ItemRepository itemRepository;
    private final ItemMapper itemMapper;

    public ItemDto getItemDto() {
        Item item = itemRepository.getItem();
        ItemDto itemDto = itemMapper.toDto(item);
        log.info(itemDto);
        return itemDto;
    }

    public Item getItem() {
        ItemDto itemDto = itemRepository.getItemDto();
        Item item = itemMapper.toItem(itemDto);
        log.info(item);
        return item;
    }
}

Тест:

@ExtendWith(MockitoExtension.class)
public class ItemServiceTest {

    @Mock
    private ItemRepository itemRepository;

    @InjectMocks
    private ItemService itemService;

    @Spy
    private ItemMapper itemMapper;

    @Test
    void shouldReturnItemDto() {
        Item mockItem = new Item(1, "mockItem", 10);
        given(itemRepository.getItem()).willReturn(mockItem);
        ItemDto itemDto = itemService.getItemDto();
        assertThat(mockItem.getName()).isEqualTo(itemDto.getName());
    }

}

build.gradle:

plugins {
    id 'org.springframework.boot' version '2.1.5.RELEASE'
    id 'java'
}

apply plugin: 'io.spring.dependency-management'

group = 'com.mapstruct.spring.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}

test {
    useJUnitPlatform {
    }
}

dependencies {
    // Mapstruct
    implementation 'org.mapstruct:mapstruct:1.3.0.Final'
    annotationProcessor 'org.mapstruct:mapstruct-processor:1.3.0.Final'
    testAnnotationProcessor 'org.mapstruct:mapstruct-processor:1.3.0.Final'

    implementation 'org.springframework.boot:spring-boot-starter-web'
    compileOnly 'org.projectlombok:lombok'
    annotationProcessor 'org.projectlombok:lombok'

    testImplementation('org.springframework.boot:spring-boot-starter-test')

    // JUnit5
    testImplementation 'org.junit.jupiter:junit-jupiter-api:5.3.2'
    testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.3.2'
    testImplementation 'org.junit.jupiter:junit-jupiter-params:5.3.2'

    // Mockito
    testImplementation 'org.mockito:mockito-core:2.23.4'
    testImplementation 'org.mockito:mockito-junit-jupiter:2.23.4'
}

1 Ответ

0 голосов
/ 28 мая 2019

@ Шпионская аннотация на

@Spy
private ItemMapper itemMapper;

не будет выполнять внедрение зависимостей сгенерированного файла класса ItemMapperImpl.Решением было бы установить

 @Spy
 private ItemMapper itemMapper = Mappers.getMapper(ItemMapper.class);

или поочередно включить подпружиненную инжекцию зависимости через @SpringBootTest(classes = {ItemMapperImpl.class}).

...