简体   繁体   中英

Mocking if condition using Mockito in springboot

How can I mock this condition using Mockito in spring boot.

@Autowired
private Config config;

if (!config.getAllowedFileFormats().contains(FilenameUtils.getExtension(multipartFile.getOriginalFilename()) {


 }

I tried using this but this seems to not be working.

@Mock
private Config config; Mockito.when(config.getAllowedFileFormats().contains(Mockito.anyString())).thenReturn(Boolean.valueOf(true));

Any Solutions.

Functionally your code is exactly the same as the following:

static class SomeClass {

    @Autowired
    private Config config;

    void method(MultipartFile multipartFile) {
        String filename = multipartFile.getOriginalFilename();
        Set<String> allowedFormats = config.getAllowedFileFormats();

        if (!allowedFormats.contains(FilenameUtils.getExtension(filename))) {

        }
    }
}

So you can either:

Mock every method in the chain:

@Test
void test() {
    Set<String> allowedFormats = new HashSet<>();
    allowedFormats.add(".exe");

    MultipartFile multipartFile = /* get your file here */ ;

    Mockito.when(multipartFile.getOriginalFilename()).thenReturn("some.exe");
    Mockito.when(config.getAllowedFileFormats()).thenReturn(allowedFormats);

    myClass.method(multipartFile);

    //verify
}

You can also static mock FilenameUtils.getExtension( but imo that's pointless as it's a helper without side effects.

Or you can pull that out into a separate method and just mock that.

@Test
void test() {
    SomeClass myClassSpy = Mockito.spy(new SomeClass());
    MultipartFile multipartFile = /* get your file here */ ;
    
    Mockito.when(myClassSpy.verifyAllowedFormat(multipartFile)).thenReturn(true);

    myClassSpy.method(multipartFile);

    //verify
}




static class SomeClass {

    @Autowired
    private Config config;

    void method(MultipartFile multipartFile) {
        if (!verifyAllowedFormat(multipartFile);) {

        }
    }

    boolean verifyAllowedFormat(MultipartFile file) {
        return config.getAllowedFileFormats()
                     .contains(FilenameUtils.getExtension(multipartFile.getOriginalFilename()));
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM