gpt4 book ai didi

java - 无法将 MapStruct 映射器注入(inject) spring-boot JUnit 测试

转载 作者:搜寻专家 更新时间:2023-10-31 20:08:32 26 4
gpt4 key购买 nike

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

应用程序运行完美,包括映射器注入(inject)。问题是映射器没有注入(inject)测试类,我收到以下错误:

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(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})

关于java - 无法将 MapStruct 映射器注入(inject) spring-boot JUnit 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50913390/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com