From ba3c5de0771a3bd22557f87ee9d9d2f50b417cf6 Mon Sep 17 00:00:00 2001 From: Sergio del Amo Date: Thu, 23 Mar 2023 17:44:20 +0100 Subject: [PATCH] test: Test ObjectUtils::coerceToBoolean --- .../io/micronaut/core/util/ObjectUtils.java | 6 ++-- .../core/util/ObjectUtilsSpec.groovy | 31 +++++++++++++++++++ 2 files changed, 34 insertions(+), 3 deletions(-) diff --git a/core/src/main/java/io/micronaut/core/util/ObjectUtils.java b/core/src/main/java/io/micronaut/core/util/ObjectUtils.java index 244c8a11355..d76f37ced46 100644 --- a/core/src/main/java/io/micronaut/core/util/ObjectUtils.java +++ b/core/src/main/java/io/micronaut/core/util/ObjectUtils.java @@ -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; + } } diff --git a/core/src/test/groovy/io/micronaut/core/util/ObjectUtilsSpec.groovy b/core/src/test/groovy/io/micronaut/core/util/ObjectUtilsSpec.groovy index e52f1a84901..167b1c2f165 100644 --- a/core/src/test/groovy/io/micronaut/core/util/ObjectUtilsSpec.groovy +++ b/core/src/test/groovy/io/micronaut/core/util/ObjectUtilsSpec.groovy @@ -1,6 +1,7 @@ package io.micronaut.core.util import spock.lang.Specification +import spock.lang.Unroll class ObjectUtilsSpec extends Specification { @@ -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 + 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") + } + }