Skip to content

Commit d925b4c

Browse files
committed
Add containsKey assertion for Map
1 parent a69843f commit d925b4c

File tree

3 files changed

+24
-0
lines changed

3 files changed

+24
-0
lines changed

CHANGELOG.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,9 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.
66

77
## [Unreleased]
88

9+
### Added
10+
- Add `containsKey` for `Map`.
11+
912
### Changed
1013
- renamed `prop` to `having` as part of effort to unify API naming, old name is deprecated.
1114
- renamed `suspendCall` to `having` as part of effort to unify API naming, old name is deprecated.

assertk/src/commonMain/kotlin/assertk/assertions/map.kt

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,14 @@ fun <K, V> Assert<Map<K, V>>.contains(element: Pair<K, V>) {
7474
contains(element.first, element.second)
7575
}
7676

77+
/**
78+
* Asserts the map contains the expected key.
79+
*/
80+
fun <K, V> Assert<Map<K, V>>.containsKey(key: K) = given {
81+
if (it.containsKey(key)) return
82+
expected("to contain key:${show(key)} but was:${show(it.keys)}")
83+
}
84+
7785
/**
7886
* Asserts the map contains at least the expected elements. The map may also contain additional elements.
7987
* @see [containsNone]

assertk/src/commonTest/kotlin/test/assertk/assertions/MapTest.kt

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,19 @@ class MapTest {
2828
}
2929
assertEquals("expected to contain:<{\"one\"=null}> but was:<{}>", error.message)
3030
}
31+
32+
@Test
33+
fun containsKey_key_present_passes() {
34+
assertThat(mapOf("one" to 1)).containsKey("one")
35+
}
36+
37+
@Test
38+
fun containsKey_key_missing_fails() {
39+
val error = assertFailsWith<AssertionError> {
40+
assertThat(mapOf("one" to 1)).containsKey("two")
41+
}
42+
assertEquals("expected to contain key:<\"two\"> but was:<[\"one\"]>", error.message)
43+
}
3144
//endregion
3245

3346
//region doesNotContain

0 commit comments

Comments
 (0)