0

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.

M06H
  • 1,675
  • 3
  • 36
  • 76
  • 1
    Can an option be to instansiate UploadRequestTasklet yourself with something like ```UploadRequestTasklet uploadRequestTasklet = new UploadRequestTasklet(localFileUploader)```? – Kaj Hejer Jan 07 '21 at 17:57
  • It can be yes if there’s no other way – M06H Jan 07 '21 at 17:58
  • you can mock/stub the Uploader or use profiles, you can check [this Q&A](https://stackoverflow.com/questions/28605833/overriding-an-autowired-bean-in-unit-tests) – Abdelghani Roussi Jan 07 '21 at 18:21

1 Answers1

1

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

Dmitrii B
  • 2,672
  • 3
  • 5
  • 14
  • I think you should indicate that this solution requires creating many version (peer profile) of his `UploadRequestTasklet ` classes with each a different "kind" of Uploader ! – Abdelghani Roussi Jan 07 '21 at 18:17
  • you can use @Profile({"dev", "local"}) for one of implementations or @Profile({"!dev", "local"})it's flexible. You can set all needed profiles for each of your beans.. – Dmitrii B Jan 07 '21 at 18:26