mapstruct 对象的 Junit 测试

Junit test for mapstruct object

我创建了一个单元测试,其中我有一个使用 PetMapperWorkMapperPersonMapper,最后,在我的代码中,我使用了 mapstrcut生成了 类 而不是我创建的接口。

下面的代码代表我的单元测试:

@SpringBootTest(classes = {PersonMapperImpl.class, PetMapperImpl.class, WorkMapperImpl.class})
public class PersonMapperTest {

    @Autowired private PersonMapperImpl personMapperImpl;

    @Test
    ...
}

我的问题是,我希望使用接口,但在这个单元测试中我直接放置了生成的 mapstruct 类。这是测试 mapstruct 对象的好方法吗?

将 MapStruct 与 Spring 一起使用时,映射器应具有 @Mapper(componentModel = "spring")。这将创建将用 @Component 注释的实现 类。为了能够在测试中使用这些接口,您需要对映射器的包进行组件扫描。

我没有在每个映射器 class 中使用 componentModel,而是将此 属性 添加到 POM 文件中的 MapStruct 插件:

<compilerArgs>
    <compilerArg>
        -Amapstruct.defaultComponentModel=spring
    </compilerArg>
</compilerArgs>

然后我只需要删除 属性 classes 如下,一切正常。

@SpringBootTest
public class PersonMapperTest {

    @Autowired private PersonMapper personMapper;

    @Test
    ...
}