diff --git a/CHANGELOG.md b/CHANGELOG.md index a47343b9..ac756b5a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,9 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0. ## [Unreleased] +### Added +- Add `containsKey` for `Map`. + ### Changed - renamed `prop` to `having` as part of effort to unify API naming, old name is deprecated. - renamed `suspendCall` to `having` as part of effort to unify API naming, old name is deprecated. diff --git a/assertk/src/commonMain/kotlin/assertk/assertions/map.kt b/assertk/src/commonMain/kotlin/assertk/assertions/map.kt index e40d28be..1f42296d 100644 --- a/assertk/src/commonMain/kotlin/assertk/assertions/map.kt +++ b/assertk/src/commonMain/kotlin/assertk/assertions/map.kt @@ -74,6 +74,14 @@ fun Assert>.contains(element: Pair) { contains(element.first, element.second) } +/** + * Asserts the map contains the expected key. + */ +fun Assert>.containsKey(key: K) = given { + if (it.containsKey(key)) return + expected("to contain key:${show(key)} but was:${show(it.keys)}") +} + /** * Asserts the map contains at least the expected elements. The map may also contain additional elements. * @see [containsNone] diff --git a/assertk/src/commonTest/kotlin/test/assertk/assertions/MapTest.kt b/assertk/src/commonTest/kotlin/test/assertk/assertions/MapTest.kt index 39184ca4..e2d3c9af 100644 --- a/assertk/src/commonTest/kotlin/test/assertk/assertions/MapTest.kt +++ b/assertk/src/commonTest/kotlin/test/assertk/assertions/MapTest.kt @@ -28,6 +28,19 @@ class MapTest { } assertEquals("expected to contain:<{\"one\"=null}> but was:<{}>", error.message) } + + @Test + fun containsKey_key_present_passes() { + assertThat(mapOf("one" to 1)).containsKey("one") + } + + @Test + fun containsKey_key_missing_fails() { + val error = assertFailsWith { + assertThat(mapOf("one" to 1)).containsKey("two") + } + assertEquals("expected to contain key:<\"two\"> but was:<[\"one\"]>", error.message) + } //endregion //region doesNotContain