Skip to content

Commit

Permalink
singleElement-with-predicate-more-info (#64)
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexCue987 committed Apr 26, 2024
1 parent b612160 commit f16d9be
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 4 deletions.
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

0 comments on commit f16d9be

Please sign in to comment.