Skip to content

Commit

Permalink
add map assertion doesNotContainKey
Browse files Browse the repository at this point in the history
  • Loading branch information
Benjamin Zweber authored and evant committed Nov 29, 2023
1 parent e46e771 commit d5f522e
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).

## [Unreleased]
- Added `doesNotContainKey` assertion for `Map`

## [0.27.0] 2023-09-13

Expand Down
8 changes: 8 additions & 0 deletions assertk/src/commonMain/kotlin/assertk/assertions/map.kt
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,14 @@ fun <K, V> Assert<Map<K, V>>.doesNotContain(element: Pair<K, V>) {
doesNotContain(element.first, element.second)
}

/**
* Asserts the map does not contain the expected key.
*/
fun <K, V> Assert<Map<K, V>>.doesNotContainKey(key: K) = given {
if (!it.containsKey(key)) return
expected("to not contain key:${show(key)} but had value: ${show(it[key])}")
}

/**
* Asserts the map does not contain any of the expected elements.
* @see [containsAtLeast]
Expand Down
12 changes: 12 additions & 0 deletions assertk/src/commonTest/kotlin/test/assertk/assertions/MapTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,18 @@ class MapTest {
}
assertEquals("expected to not contain:<{\"two\"=2}> but was:<{\"one\"=1, \"two\"=2}>", error.message)
}

@Test fun doesNotContainKey_key_missing_passes() {
assertThat(emptyMap<String, Int>()).doesNotContainKey("one")
}

@Test fun doesNotContainKey_key_present_fails() {
val error = assertFailsWith<AssertionError> {
assertThat(mapOf("one" to 1)).doesNotContainKey("one")
}
assertEquals("expected to not contain key:<\"one\"> but had value: <1>", error.message)
}

//endregion

//region containsNone
Expand Down

0 comments on commit d5f522e

Please sign in to comment.