无法将MapStruct映射器注入到Spring-boot JUnit测试中

use*_*865 5 java spring-boot mapstruct

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

该应用程序完美运行,包括mapper注入。问题是映射器没有注入到测试类中,并且出现以下错误:

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)}
Run Code Online (Sandbox Code Playgroud)

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

这是映射器类:

@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);
}
Run Code Online (Sandbox Code Playgroud)

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

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

private WorkflowMapper workflowMapper;

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

...some code
Run Code Online (Sandbox Code Playgroud)

单元测试课:

@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...
}
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激。

Mak*_*oto 6

乍一看,您没有将要测试的 bean 作为组件扫描的一部分包含在内。

您希望更新您的@ComponentScan配置以包含它。

@ComponentScan(basePackageClasses = {WorkflowMapperTest.class,
                                     WorkflowMapper.class,
                                     WorkflowMapperImpl.class})
Run Code Online (Sandbox Code Playgroud)

  • 如果您不更改生成的映射器的包,则仅包含“WorkflowMapper”就足够了 (2认同)