【问题标题】:Junit test for mapstruct objectmapstruct 对象的 Junit 测试
【发布时间】:2019-12-13 08:44:28
【问题描述】:

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

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

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

    @Autowired private PersonMapperImpl personMapperImpl;

    @Test
    ...
}

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

【问题讨论】:

标签: junit junit5 mapstruct


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

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

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

    @SpringBootTest
    public class PersonMapperTest {
    
        @Autowired private PersonMapper personMapper;
    
        @Test
        ...
    }
    

    【讨论】:

      猜你喜欢
      • 2011-03-26
      • 1970-01-01
      • 2017-12-29
      • 1970-01-01
      • 1970-01-01
      • 2023-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多