【问题标题】:MapStruct mapper not injected in Spring Unit TestsMapStruct 映射器未在 Spring 单元测试中注入
【发布时间】:2017-11-03 22:38:08
【问题描述】:

我正在使用一个由 MapStruct 生成的映射器:

@Mapper
public interface CustomerMapper {
   Customer mapBankCustomerToCustomer(BankCustomerData bankCustomer);
}

默认组件模型为spring(在pom.xml中设置)

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

我有一项服务,我在其中注入客户映射器,并且在运行应用程序时工作正常

@Autowired
private CustomerMapper customerMapper;

但是当我运行涉及@SpringBootTest 的单元测试时

@SpringBootTest
@AutoConfigureMockMvc
@RunWith(SpringRunner.class)
public class SomeControllerTest {

    @Mock
    private SomeDependency someDependency;

    @InjectMocks
    private SomeController someController;

    @Test
    public void shouldDoSomething() {
        ...
    }

}

我得到一个 org.springframework.beans.factory.UnsatisfiedDependencyException

通过字段'customerMapper'表达的不满足的依赖关系

【问题讨论】:

  • 在通过 IDE、Maven 或两者调用测试时是否会发生这种情况?
  • 如果它是 IDE-only,我的猜测是 target/generated-sources 不会作为源文件夹添加到 IDE 项目中。
  • 我只使用 IDE 运行测试,但我确实将 generate-sources 文件夹添加为源文件夹,否则我的应用程序将无法运行。

标签: spring unit-testing dependency-injection mapstruct


【解决方案1】:

我关注了这个answer,我的问题在我将建议的行粘贴到我的 build.gradle 文件中时很快就解决了

【讨论】:

    【解决方案2】:

    当您通过 IDE 运行测试时,有两种可能性:

    1. Eclipse 或 IntelliJ 正在使用注释处理器,您需要正确设置它们。
    2. Eclipse 或 IntelliJ 不会从 maven 编译器中选择编译器选项

    要排除可能性,请针对每种情况执行以下操作:

    1. 确保将 IDE 配置为运行 APT。看看here你如何设置它。从 IDE 运行构建并检查是否生成了映射器类
    2. 如果有的话,它们很可能是使用默认组件模型生成的。要解决此问题,您有两种选择:
      1. 使用@Mapper(componentModel = "spring")。我个人更喜欢这个选项,因为你是独立于 IDE 的。您也可以使用可以申请的@MapperConfig
      2. 使用注释选项配置 IDE。对于 IntelliJ,在 Settings -> Build, Execution, Deployment -> Compiler -> Annotation Processors 中添加编译器参数,其中有一个名为 Annotation Processor Options 的部分添加 mapstruct.defaultComponentModel 作为选项名称和 spring 作为值。我不知道如何为 Eclipse 做这件事

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-15
      • 2017-12-29
      • 1970-01-01
      • 2021-06-11
      • 2020-08-02
      • 1970-01-01
      • 1970-01-01
      • 2019-05-05
      相关资源
      最近更新 更多