Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add containsKey assertion for Map #561

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
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 @@ -74,6 +74,14 @@ fun <K, V> Assert<Map<K, V>>.contains(element: Pair<K, V>) {
contains(element.first, element.second)
}

/**
* Asserts the map contains the expected key.
*/
fun <K, V> Assert<Map<K, V>>.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]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<AssertionError> {
assertThat(mapOf("one" to 1)).containsKey("two")
}
assertEquals("expected to contain key:<\"two\"> but was:<[\"one\"]>", error.message)
}
//endregion

//region doesNotContain
Expand Down