Java @使用MapStruct的SpringBootTest需要Impl
我有以下测试:Java @使用MapStruct的SpringBootTest需要Impl,java,spring-boot-test,mapstruct,Java,Spring Boot Test,Mapstruct,我有以下测试: @SpringBootTest(classes = {SomeService.class, DtoMapperImpl.class}) class SomeServiceTest { 以及以下绘图程序: @Mapper(componentModel = "spring") public interface DtoMapper { EntityDto toDto(Entity entity); } 我没有更改包(这意味着DtoMapperImpl与D
@SpringBootTest(classes = {SomeService.class, DtoMapperImpl.class})
class SomeServiceTest {
以及以下绘图程序:
@Mapper(componentModel = "spring")
public interface DtoMapper {
EntityDto toDto(Entity entity);
}
我没有更改包(这意味着DtoMapperImpl与DtoMapper在同一个包中)
一旦我将Impl更改为interface,我的测试就会失败:
@SpringBootTest(classes = {SomeService.class, DtoMapper.class})
class SomeServiceTest {
原因:
org.springframework.beans.factory.unsatifiedDependencyException:
创建名为“someService”的bean时出错:未满足依赖关系
通过构造函数参数2表示;嵌套异常是
org.springframework.beans.factory.noSuchBean定义异常:否
“DtoMapper”类型的合格bean可用:至少应为1
符合autowire候选资格的bean。依赖项批注:{}
你能建议解决这个问题的最佳方法吗?我使用的是MapStruct 1.3.1。最终版创建以下配置(应指向映射器所在的位置): 和修改切片:
@SpringBootTest(classes = {SomeService.class, MappersConfig.class})
class SomeServiceTest {
问题实际上与MapStruct无关,而是如何使用
SpringBootTest#类
SpringBootTest
中的类
旨在提供应用于在测试中加载的组件
从JavaDoc:
用于加载ApplicationContext
的组件类。也可以使用@ContextConfiguration(classes=…)
指定。如果没有定义显式类,测试将在返回到@SpringBootConfiguration
搜索之前查找嵌套的@Configuration
类。
返回:
用于加载应用程序上下文的组件类
在您的案例中,您有两个类:
SomeService
——我假设它是一个用@Service
注释的类,Spring将正确加载它
DtoMapper
-这是MapStruct映射器,它是一个接口,而不是组件。测试所需的组件是DtoMapperImpl
您有几个选项可以修复此问题:
使用Impl类
您可以在SpringBootTest#类中使用DtoMapperImpl
(Spring组件类),然后测试将加载正确的组件
使用自定义配置类,该类将对映射器进行组件扫描
然后在您的SpringBootTest#类中使用它。例如
@SpringBootTest(classes = {SomeService.class, MappersConfig.class})
class SomeServiceTest {
...
}
因为您使用的@SpringBootTest
错误。也就是说,对于spring boot集成测试,您要测试您的服务,然后不要为此使用@SpringBootTest
。很抱歉,这并不能回答我的问题,因为您使用了错误的工具进行此项工作,或者在本例中使用了错误的工具。您可以编写一个完整的集成测试(然后删除类
部分),也可以为您的服务编写一个简单的单元测试,并通过从MapStruct本身获取映射器来手动注入映射器。很抱歉,我只想指出,您的评论与此问题无关。如果您想讨论意识形态,如何编写集成测试,我很乐意在这个问题之外这样做。Mods,请清理它不是关于ideologie而是关于在你的测试中使用错误的工具,这是我试图解释的。谢谢,这是我之前发布的。你能在第二个选项中复制我的代码样本吗?我会把它标记为答案?
@TestConfiguration
@ComponentScan("com.example.mapper")
public class MappersConfig {
}
@SpringBootTest(classes = {SomeService.class, MappersConfig.class})
class SomeServiceTest {
...
}