java - 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);
}
}
出现异常的测试类。正如我所提到的,我尝试添加AddressConverter
到ContextConfiguration
. 我还尝试通过添加来完全模拟它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.
}
}
解决方案
我相信你需要用@MockBean 改变@InjectMock
推荐阅读
- css - 使用 vue/nuxt 将样式属性附加到所有(锚)元素
- java - 如何运行输出文本的进程并将该文本在输出时写入 Javafx textArea?
- excel - 使用 VBA 从 excel 中删除连接时出错
- java - 如何用两条单独的数据解析一行文本?
- php - 教义 ORM:未定义的偏移量 2
- 32bit-64bit - RISC-V 32/64 位兼容性问题
- dynamic - 基于度量的数据查找
- machine-learning - 如何将一对向量提供给分类器以对相似/不相似进行分类
- powershell - 尝试编写 PS 脚本将数据从多个 .csv 转储到单个 csv
- powershell - 为什么变量不会更新?