繁体   English   中英

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

[英]Cannot inject MapStruct mapper into spring-boot JUnit test

我正在尝试使用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...
}

任何帮助将不胜感激。

一目了然,您不要将要测试的bean包含在组件扫描中。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM