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

shouldHaveElementAt-more-info #3985

Merged
merged 3 commits into from
May 19, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Expand Up @@ -15,12 +15,18 @@ fun <T> Array<T>.shouldNotHaveElementAt(index: Int, element: T) = asList().shoul
fun <T> List<T>.shouldNotHaveElementAt(index: Int, element: T) = this shouldNot haveElementAt(index, element)

fun <T, L : List<T>> haveElementAt(index: Int, element: T) = object : Matcher<L> {
override fun test(value: L) =
MatcherResult(
index < value.size && value[index] == element,
{ "Collection ${value.print().value} should contain ${element.print().value} at index $index" },
override fun test(value: L): MatcherResult {
val (passed, errorDescription) = when {
index >= value.size -> false to "but collection was shorter"
value[index] != element -> false to "but element was different. Expected: <${element.print().value}>, but was <${value[index].print().value}>"
else -> true to ""
}
return MatcherResult(
passed,
{ "Collection ${value.print().value} should contain ${element.print().value} at index $index, $errorDescription" },
{ "Collection ${value.print().value} should not contain ${element.print().value} at index $index" }
)
}
}

infix fun <T> Iterable<T>.shouldExist(p: (T) -> Boolean) = toList().shouldExist(p)
Expand Down
Expand Up @@ -143,6 +143,16 @@ class CollectionMatchersTest : WordSpec() {
tests should haveElementAt(0, TestSealed.Test1("test1"))
tests.shouldHaveElementAt(1, TestSealed.Test2(2))
}
"indicate than collection is too short" {
AlexCue987 marked this conversation as resolved.
Show resolved Hide resolved
shouldThrowAny {
listOf("a", "b", "c").shouldHaveElementAt(3, "b")
}.message shouldBe "Collection [\"a\", \"b\", \"c\"] should contain \"b\" at index 3, but collection was shorter"
}
"indicate that elements differ" {
shouldThrowAny {
listOf("a", "b", "c").shouldHaveElementAt(2, "b")
}.message shouldBe "Collection [\"a\", \"b\", \"c\"] should contain \"b\" at index 2, but element was different. Expected: <\"b\">, but was <\"c\">"
}
}

"containNull()" should {
Expand Down