Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

test: Test ObjectUtils::coerceToBoolean #8996

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions core/src/main/java/io/micronaut/core/util/ObjectUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -88,15 +88,15 @@ public static boolean coerceToBoolean(@Nullable Object object) {
} else if (object instanceof Number n) {
return n.doubleValue() > 0;
} else if (object instanceof Collection<?> col) {
return col.size() > 0;
return !col.isEmpty();
} else if (object instanceof Map<?, ?> col) {
return col.size() > 0;
} else if (object instanceof Object[] array) {
return array.length > 0;
} else if (object instanceof Optional<?> opt) {
return opt.isPresent();
} else {
return true;
}
return true;

}
}
31 changes: 31 additions & 0 deletions core/src/test/groovy/io/micronaut/core/util/ObjectUtilsSpec.groovy
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package io.micronaut.core.util

import spock.lang.Specification
import spock.lang.Unroll

class ObjectUtilsSpec extends Specification {

Expand All @@ -21,4 +22,34 @@ class ObjectUtilsSpec extends Specification {
o3 << ["abc", null, "xyz", null]
}

@Unroll("ObjectUtils.coerceToBoolean with argument #obj returns #expected")
def "ObjectUtils::coerceToBoolean"(boolean expected, Object obj) {
expect:
expected == ObjectUtils.coerceToBoolean(obj)
where:
expected | obj
false | null
false | Boolean.FALSE
true | Boolean.TRUE
true | "string"
false | ""
false | 0L
false | new BigDecimal("0.0")
false | 0
false | 0.0f
true | 1L
true | new BigDecimal("0.1")
true | 1
false | -1
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In Apache Groovy a negative number evaluates to true. Not sure if we should change this to return true for negative numbers as well.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah I think the logic for numbers is questionable. We should return true as well

true | 0.1f
false | Collections.emptyList()
true | Collections.singletonList("1")
false | Collections.emptyMap()
true | Collections.singletonMap("foo", "bar")
false | new String[] {}
true | new String[] {"foo"}
false | Optional.empty()
true | Optional.of("foo")
}

}