Rip*_*man 12 java spring unit-testing dependency-injection
我有一个类,我想在组件扫描时排除.我使用下面的代码来做到这一点,但似乎没有工作,虽然一切似乎都是正确的
@ComponentScan(basePackages = { "common", "adapter", "admin"}, excludeFilters = { @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = ServiceImpl.class) })
Run Code Online (Sandbox Code Playgroud)
实际上我想要有"ServiceImpl"类,它实现了"服务"接口,正在我的其余api逻辑中使用,在进行api的集成测试时,我想要排除这个实现并加载模拟的实现.但这似乎并没有发生,因为即使使用上面我得到以下错误
No qualifying bean of type [admin.Service] is defined: expected single matching bean but found 2: ServiceMockImpl,ServiceImpl
Run Code Online (Sandbox Code Playgroud)
我花了太多时间在这上面但没有任何作用.
任何帮助表示赞赏.
Rip*_*man 35
经过大量的工作和研究,我注意到Spring在组件扫描方面的行为并不奇怪.
文物是这样的:
"ServiceImpl"是实现"服务"接口的真正实现类."ServiceMockImpl"是实现"服务"接口的模拟植入类.
我想调整组件扫描,以便它只加载"ServiceMockImpl"而不加载"ServiceImpl".
我必须在测试配置类的"@ComponentScan"中添加"@ ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE,value = ServiceImpl.class)",以从组件扫描中排除该特定类.但是即使在完成上述更改并且测试失败之后,这两个类都被加载了.
经过大量的工作和研究后,我发现"ServiceImpl"正在加载,因为其他类正在加载,并且其中包含所有包的"@ComponentScan".所以我添加了代码以从组件扫描中排除"Application"类,如下所示"@ ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE,value = Application.class)".
之后它按预期工作.
代码如下
@ComponentScan(
excludeFilters = {
@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = OAuthCacheServiceImpl.class),
@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = Application.class)
},
basePackages = {
"common", "adapter", "admin"
}
)
Run Code Online (Sandbox Code Playgroud)
我已经看到很多关于组件扫描的问题很长时间没有答案,因此我想添加这些细节,因为它可能会帮助将来的某些人.
HTH ...