[英]How to use different implementation in unit test when class injects with Qualifier
I have a spring bean component which I want to unit test for example:我有一个 spring bean 组件,我想对其进行单元测试,例如:
@Component
public class UploadRequestTasklet implements Tasklet {
private final Uploader fileUploader;
public UploadRequestTasklet(@Qualifier("mainUploader") final Uploader fileUploader) {
this.fileUploader = fileUploader;
}
@Override
public RepeatStatus execute(final StepContribution stepContribution,
final ChunkContext chunkContext) throws IOException, InterruptedException {
Info result = fileUploader.remoteUpload(context, info);
return RepeatStatus.FINISHED;
}
}
I have multiple different implementation of Uploader
interface.我有多个不同的Uploader
接口实现。 For production, I use the mainUploader
which uploads files to remote server.对于生产,我使用将文件上传到远程服务器的mainUploader
。 For integration and unit test, I want to use the localFileUploader
implementation.对于集成和单元测试,我想使用localFileUploader
实现。 The uploader classes live outside of my project and I have imported these classes from another project using maven dependency.上传器类位于我的项目之外,我已经使用 maven 依赖项从另一个项目中导入了这些类。
My question is, how can I override the mainuploader and in unit test, use the localFileUploader version?我的问题是,如何覆盖 mainuploader 并在单元测试中使用 localFileUploader 版本?
the class UploadRequestTasklet has Qualifier annotation specifying to use main implementation which I cannot seem to override in unit test. class UploadRequestTasklet 有限定符注释指定使用我似乎无法在单元测试中覆盖的主要实现。
You can use @Profile together with your interface Tasklet implementations, for example您可以将@Profile 与您的接口 Tasklet 实现一起使用,例如
@Component
@Profile("local")
public class UploadRequestTasklet implements Tasklet {
...
}
for a run that set jvm args -Dspring.profiles.active=local if you want to run test by maven or gradle.对于设置 jvm args -Dspring.profiles.active=local的运行,如果您想通过 maven 或 gradle 运行测试。 But, if you want to do it by IDE you can set @ActiveProfiles("local") with your component但是,如果您想通过 IDE 执行此操作,您可以使用您的组件设置@ActiveProfiles("local")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.