Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
307 views
in Technique[技术] by (71.8m points)

java - 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:

@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. For production, I use the mainUploader which uploads files to remote server. For integration and unit test, I want to use the localFileUploader implementation. The uploader classes live outside of my project and I have imported these classes from another project using maven dependency.

My question is, how can I override the mainuploader and in unit test, use the localFileUploader version?

the class UploadRequestTasklet has Qualifier annotation specifying to use main implementation which I cannot seem to override in unit test.

question from:https://stackoverflow.com/questions/65617530/how-to-use-different-implementation-in-unit-test-when-class-injects-with-qualifi

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use @Profile together with your interface Tasklet implementations, for example

    @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. But, if you want to do it by IDE you can set @ActiveProfiles("local") with your component

see more here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...