无法将MapStruct映射器注入spring-boot JUnit测试

时间:2018-06-18 16:00:33

标签: java spring-boot mapstruct

我正在尝试使用componentModel="spring"为MapStruct映射器编写单元测试。

该应用程序运行良好,包括映射器注入。 问题是映射器没有注入测试类,我收到以下错误:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.onap.sdc.workflow.api.mapping.WorkflowMapperTest': Unsatisfied dependency expressed through field 'workflowMapper'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.onap.sdc.workflow.services.mappers.WorkflowMapper' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

我正在使用intellij IDEA并标记了target \ generated-sources。

这是mapper类:

@Mapper(componentModel = "spring")
public interface WorkflowMapper {

@Mapping(source = "properties", target = "category", qualifiedByName = "propertiesToCategoryMapper")
Workflow itemToWorkflow(Item item);

@Mapping(source = "category", target = "properties", qualifiedByName = "categoryToPropertiesMapper")
@InheritInverseConfiguration
Item workflowToItem(Workflow workflow);

@Named("propertiesToCategoryMapper")
default String customPropertiesToCategoryMapper(Map<String, Object> properties) {
    return String.class.cast(properties.get(WorkflowProperty.CATEGORY));
}

@Named("categoryToPropertiesMapper")
default Map<String, Object> customCategoryToPropertiesMapper(String category) {
    return Collections.singletonMap(WorkflowProperty.CATEGORY, category);
}

我在以下代码段中使用此映射器:

@Service("workflowManager")
public class WorkflowManagerImpl implements WorkflowManager {

private WorkflowMapper workflowMapper;

@Autowired
public WorkflowManagerImpl(WorkflowMapper workflowMapper) {
    this.workflowMapper = workflowMapper;
}

...some code

单元测试类:

@ContextConfiguration(classes = 
WorkflowMapperTest.WorkflowMapperSpringTestConfig.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class WorkflowMapperTest {

@Configuration
@ComponentScan(basePackageClasses = WorkflowMapperTest.class)
public static class WorkflowMapperSpringTestConfig { }

@Autowired
WorkflowMapper workflowMapper;

@Test
public void shouldMapItemPropertyToWorkflowCategory() {
    ...some code...
}

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:3)

乍一看,您不会将要测试的bean包含在组件扫描中。

您需要更新@ComponentScan配置以包含它。

@ComponentScan(basePackageClasses = {WorkflowMapperTest.class,
                                     WorkflowMapper.class,
                                     WorkflowMapperImpl.class})