Spring Boot Test 未加载带有 @Component 注释的类

Har*_*hit 5 java integration-testing orika spring-boot spring-boot-test

在我的 Spring Boot 应用程序中,我正在使用 @SpringBootTest 编写集成测试。我正在使用配置类并在其上使用@ComponentScan,但它没有加载组件并且测试失败。

应用程序配置.java

@Configuration
@ComponentScan(basePackages = { "com.example.inventory" })
public class ApplicationConfig {

    @Bean
    public MapperFactory mapperFactory() {
        return new DefaultMapperFactory.Builder().build();
    }
}
Run Code Online (Sandbox Code Playgroud)

这里的 DefaultMapperFactory 是 Orika Mapper 的一部分,我用它来将模型转换为 DTO,反之亦然。

ProductSupplierIntegrationTests.java

@SpringBootTest(classes = ApplicationConfig.class)
@RunWith(SpringRunner.class)
@AutoConfigureMockMvc
public class ProductSupplierIntegrationTests {
    // tests
}
Run Code Online (Sandbox Code Playgroud)

产品供应商模式

@Entity
public class ProductSupplier {

    @Id
    @GeneratedValue
    private Long id;

    private Long supplierId;

    @ManyToOne
    private Supplier supplier;

    private Double buyPrice;

    private boolean defaultSupplier;

    // getters and setters
}
Run Code Online (Sandbox Code Playgroud)

供应商模式

@Entity
public class Supplier {

    @Id
    @GeneratedValue
    private Long id;

    private String firstName;

    private String lastName;

    private String email;

    // getters and setters
}
Run Code Online (Sandbox Code Playgroud)

产品供应商DTO

public class ProductSupplierDTO {

    private Long supplierId;

    private String firstName;

    private String lastName;

    private String email;

    private Double buyPrice;

    private Boolean defaultSupplier;

    // getters and setters
}
Run Code Online (Sandbox Code Playgroud)

Orika 映射器配置

package com.example.inventory.mapper;

@Component
public class ProductSupplierMapper implements OrikaMapperFactoryConfigurer {

    @Override
    public void configure(MapperFactory orikaMapperFactory) {
        orikaMapperFactory.classMap(ProductSupplier.class, ProductSupplierDTO.class).exclude("id")
                .field("supplier.firstName", "firstName").field("supplier.lastName", "lastName")
                .field("supplier.email", "email").byDefault().register();
    }

}
Run Code Online (Sandbox Code Playgroud)

当我运行应用程序时,spring加载映射器并将其注册在上下文中,并按照我指定的方式在pojo之间进行转换,但是当我运行集成测试时,未加载映射器,并且使用默认的orika配置转换pojo,并且字段firstName,lastName和email不是映射到 DTO 中。

谁能告诉我测试配置中缺少什么?