首页 > 解决方案 > Mapstruct 抽象映射器无法在单元测试中模拟组件

问题描述

使用 MapStruct,我创建了一个抽象类的映射器。我决定将映射器从接口转换为抽象,以便使用AddressConverter本身正在使用名为CountryService.

尽管映射工作正常,但在单元测试中它抱怨AddressConverter找不到合格 bean 的组件。

我尝试将它添加到ContextConfiguration映射器,但问题将链接到嵌套组件,直到repository我无法添加它,ContextConfiguration因为它是一个接口。

例外

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.mind.microservice.mapper.converter.AddressConverter' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1509)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1065)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:584)
    ... 42 more

映射器类。我尝试AddressConverter在注释上添加uses属性。@Mapper但是异常转移到了AddressConverter我上面提到的下一个组件。

@Mapper(componentModel = "spring", uses = {
        GenericMapper.class,
        Size.class
})
public abstract class StudentMapper{

    @Autowired
    private AddressConverter addressConverter;

    @Mappings({
            @Mapping(target = "address", source = "student", qualifiedByName = "formatAddress"),
    })
    public abstract StudentEntity map(Student student);

    @Named("formatAddress")
    public String formatAddress(Student student){
        return this.addressConverter.buildAddress(student);
    }
    
}

AddressCoverter

@Component
@AllArgsConstructor
public class AddressConverter {

    private final CountryService countryService;

    public String buildAddress(Student student){
        return this.countryService.countryFormatter(student.getCountry); 
    }
}

出现异常的测试类。正如我所提到的,我尝试添加AddressConverterContextConfiguration. 我还尝试通过添加来完全模拟它InjectMocks

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {
        GenericMapper.class,
        Size.class
})
public class StudentMapperTest{

    @Autowired
    private StudentMapper MAPPER;
     
    //also @Autowired was used and also I removed it completely, still the same exception
    @InjectMocks 
    private AddressConverter addressConverter;

    @Test
    public void testStudentToStudentEntityMapping() {
        Student randomStudent = ObjectHandler.random(Student.class);

      //...the rest of the test but it doesn't even enter, so it doesn't affect the outcome.
   }
 
}

标签: javaspring-bootjunitdependency-injectionmapstruct

解决方案


我相信你需要用@MockBean 改变@InjectMock


推荐阅读