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

singleElement-with-predicate-more-info #3986

Open
wants to merge 1 commit into
base: master
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,17 @@ fun <T> singleElement(t: T): Matcher<Collection<T>> = object : Matcher<Collectio
fun <T> singleElement(p: (T) -> Boolean): Matcher<Collection<T>> = object : Matcher<Collection<T>> {
override fun test(value: Collection<T>): MatcherResult {
val filteredValue: List<T> = value.filter(p)
val indexesOfMatchingElements = value.mapIndexedNotNull { index, element ->
if(p(element)) index else null
}
val mismatchDescription = when(indexesOfMatchingElements.size) {
0 -> "no elements matched"
1 -> ""
else -> "elements with the following indexes matched: ${indexesOfMatchingElements.print().value}"
}
return MatcherResult(
filteredValue.size == 1,
{ "Collection should have a single element by a given predicate but has ${filteredValue.size} elements: ${value.print().value}" },
indexesOfMatchingElements.size == 1,
{ "Collection should have a single element by a given predicate, but $mismatchDescription, and the whole collection was: ${value.print().value}" },
{ "Collection should not have a single element by a given predicate" }
)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -261,11 +261,11 @@ class CollectionMatchersTest : WordSpec() {

shouldThrow<AssertionError> {
listOf(1) shouldHave singleElement { e -> e == 2 }
}.shouldHaveMessage("Collection should have a single element by a given predicate but has 0 elements: [1]")
}.shouldHaveMessage("Collection should have a single element by a given predicate, but no elements matched, and the whole collection was: [1]")

shouldThrow<AssertionError> {
listOf(2, 2) shouldHave singleElement { e -> e == 2 }
}.shouldHaveMessage("Collection should have a single element by a given predicate but has 2 elements: [2, 2]")
}.shouldHaveMessage("Collection should have a single element by a given predicate, but elements with the following indexes matched: [0, 1], and the whole collection was: [2, 2]")
}
}

Expand Down