Skip to content

Commit

Permalink
singleElement-more-info (#61)
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexCue987 committed Apr 26, 2024
1 parent b612160 commit e5ce1cf
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,15 @@ fun <T> singleElement(t: T): Matcher<Collection<T>> = object : Matcher<Collectio
expected = t.print().value,
)
} else {
val elementFoundAtIndexes = value.mapIndexedNotNull {
index, element ->
if(element == t) index else null
}
val foundAtMessage = if(elementFoundAtIndexes.isEmpty()) "Element not found in collection"
else "Element found at index(es): ${elementFoundAtIndexes.print().value}"
MatcherResult(
passed = false,
failureMessageFn = { "Collection should be a single element of $t but has ${value.size} elements: ${value.print().value}" },
failureMessageFn = { "Collection should be a single element of $t but has ${value.size} elements: ${value.print().value}. $foundAtMessage." },
negatedFailureMessageFn = { "Collection should not be a single element of $t" },
)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -250,7 +250,11 @@ class CollectionMatchersTest : WordSpec() {

shouldThrow<AssertionError> {
listOf(1, 2) shouldBe singleElement(2)
}.shouldHaveMessage("Collection should be a single element of 2 but has 2 elements: [1, 2]")
}.shouldHaveMessage("Collection should be a single element of 2 but has 2 elements: [1, 2]. Element found at index(es): [1].")

shouldThrow<AssertionError> {
listOf(1, 2) shouldBe singleElement(3)
}.shouldHaveMessage("Collection should be a single element of 3 but has 2 elements: [1, 2]. Element not found in collection.")
}
}

Expand Down

0 comments on commit e5ce1cf

Please sign in to comment.