'isEmpty() on an ArrayList results in false although its size is 0

In a test I inject a mock to another class which seems to work properly. However, when I check the ArrayList if it is empty the result is false although its length/size is 0. How can this happen and how can I solve this problem?

@Slf4j
@Configuration
@RequiredArgsConstructor
@Setter(onMethod_ = @SuppressFBWarnings({"EI_EXPOSE_REP2", "EI_EXPOSE_REP"}))
@Getter(onMethod_ = @SuppressFBWarnings({"EI_EXPOSE_REP2", "EI_EXPOSE_REP"}))
@EnableConfigurationProperties(MyProperties.class)
public class MyConfig {

    private final MyProperties myProperties;

    private final GenericApplicationContext applicationContext;

    @PostConstruct
    void init() {
        Objects.requireNonNull(myProperties, "myProperties needs not to be null.");
        if (/*myProperties.getApps().size() == 0 || */myProperties.getApps().isEmpty()) {
            log.info("bla bla bla");
        } else {
            ...
        }
    }
}

Here's my test class:

@ExtendWith(MockitoExtension.class)
class MyConfigTest {

    @Mock
    MyProperties myPropertiesMock;

    @InjectMocks
    MyConfig myConfig;

    ApplicationContextRunner contextRunner;

    @Test
    void should_check_for_empty_apps() {
        contextRunner = new ApplicationContextRunner()
            .withPropertyValues("foobar.apps[0].name=", "foobar.apps[0].baseUrl=", "foobar.apps[0].basePath=")
        ;

        List apps = Mockito.mock(ArrayList.class);
        when(myPropertiesMock.getApps()).thenReturn(apps);

        myConfig.init();

        contextRunner.run(context -> {
            assertThat(apps.size()).isEqualTo(0);
        });
    }
}

The properties class:

@Slf4j
@Validated
@Data
@Setter(onMethod_ = @SuppressFBWarnings({"EI_EXPOSE_REP2", "EI_EXPOSE_REP"}))
@Getter(onMethod_ = @SuppressFBWarnings({"EI_EXPOSE_REP2", "EI_EXPOSE_REP"}))
@ConfigurationProperties(prefix = MyProperties.CONFIG_PREFIX)
public class MyProperties implements LoggableProperties {

    public static final String CONFIG_PREFIX = "foobar";

    @Valid
    @NestedConfigurationProperty
    private List<MyEndpoint> apps = new ArrayList<>();

    @Data
    public static class MyEndpoint {
//        @NotNull
//        @NotEmpty
        private String baseUrl = "";

        private String basePath = "";

//        @NotNull
//        @NotEmpty
        private String name = "";
    }
}


Solution 1:[1]

‘app’ is a mock. You have to mock any method that you use, otherwise it retrieve type’s default value.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1