diff --git a/CHANGELOG.md b/CHANGELOG.md index a47343b9..4ddd0f06 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0. - the receiver types for `isTrue()`, `isFalse()`, and `isInstanceOf()` have been widened to operate on nullable values. - signature of `isIn` and `isNotIn` has been changed to ensure at least two items are supplied. - added assertions `isIn(Iterable)` and `isNotIn(Iterable)` +- added transformers `Map.havingKeys()` and `Map.havingValues()` ## [0.28.1] 2024-04-17 diff --git a/assertk/src/commonMain/kotlin/assertk/assertions/map.kt b/assertk/src/commonMain/kotlin/assertk/assertions/map.kt index e40d28be..f99656d4 100644 --- a/assertk/src/commonMain/kotlin/assertk/assertions/map.kt +++ b/assertk/src/commonMain/kotlin/assertk/assertions/map.kt @@ -173,3 +173,33 @@ fun Assert>.key(key: K): Assert = transform(appendName(show( expected("to have key:${show(key)}") } } + +/** + * Returns an assert that has a collection of the keys in the map. + * ``` + * assertThat(mapOf("key" to "value")).havingKeys().containsOnly("key") + * ``` + * @see havingValues + */ +fun Assert>.havingKeys(): Assert> = transform { + if (it.isEmpty()) { + expected("map to not be empty") + } else { + it.keys + } +} + +/** + * Returns an assert that has a collection of the values in the map. + * ``` + * assertThat(mapOf("key" to "value")).havingValues().containsOnly("value") + * ``` + * @see havingKeys + */ +fun Assert>.havingValues(): Assert> = transform { + if (it.isEmpty()) { + expected("map to not be empty") + } else { + it.values + } +} \ No newline at end of file diff --git a/assertk/src/commonTest/kotlin/test/assertk/assertions/MapTest.kt b/assertk/src/commonTest/kotlin/test/assertk/assertions/MapTest.kt index 39184ca4..ef17c2a5 100644 --- a/assertk/src/commonTest/kotlin/test/assertk/assertions/MapTest.kt +++ b/assertk/src/commonTest/kotlin/test/assertk/assertions/MapTest.kt @@ -287,4 +287,34 @@ class MapTest { assertEquals("expected [subject] to have key:<\"wrong\">", error.message) } //endregion + + //region havingKeys + @Test + fun havingKeys_empty_list_fails() { + val error = assertFailsWith { + assertThat(emptyMap()).havingKeys() + } + assertEquals("expected map to not be empty", error.message) + } + + @Test + fun havingKeys_assertion_passes() { + assertThat(mapOf("key" to "value")).havingKeys().containsOnly("key") + } + //endregion + + //region havingValues + @Test + fun havingValues_empty_list_fails() { + val error = assertFailsWith { + assertThat(emptyMap()).havingKeys() + } + assertEquals("expected map to not be empty", error.message) + } + + @Test + fun havingValues_assertion_passes() { + assertThat(mapOf("key" to "value")).havingValues().containsOnly("value") + } + //endregion }