Skip to content

Commit

Permalink
Merge pull request #395 from olafurpg/array-eq
Browse files Browse the repository at this point in the history
Improve error message when comparing arrays with same elements
  • Loading branch information
olafurpg authored Jul 26, 2021
2 parents de84d57 + 02c092f commit 0354373
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
22 changes: 22 additions & 0 deletions munit/shared/src/main/scala/munit/Assertions.scala
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,28 @@ trait Assertions extends MacroCompat.CompileErrorMacro {
)(implicit loc: Location, ev: B <:< A): Unit = {
StackTraces.dropInside {
if (obtained != expected) {

(obtained, expected) match {
case (a: Array[_], b: Array[_]) if a.sameElements(b) =>
// Special-case error message when comparing arrays. See
// https://github.com/scalameta/munit/pull/393 and
// https://github.com/scalameta/munit/issues/339 for a related
// discussion on how MUnit should handle array comparisons. Other
// testing frameworks have special cases for arrays so the
// comparison succeeds as long as `sameElements()` returns true.
// MUnit chooses instead to fail the test with a custom error
// message because arrays have reference equality, for better or
// worse, and we should not hide that fact from our users.
failComparison(
"arrays have the same elements but different reference equality. " +
"Convert the arrays to a non-Array collection if you intend to assert the two arrays have the same elements. " +
"For example, `assertEquals(a.toSeq, b.toSeq)",
obtained,
expected
)
case _ =>
}

Diffs.assertNoDiff(
munitPrint(obtained),
munitPrint(expected),
Expand Down
10 changes: 10 additions & 0 deletions tests/shared/src/test/scala/munit/AssertionsSuite.scala
Original file line number Diff line number Diff line change
Expand Up @@ -58,4 +58,14 @@ class AssertionsSuite extends BaseSuite {
|""".stripMargin
)
}
test("array-sameElements") {
val e = intercept[ComparisonFailException] {
assertEquals(Array(1, 2), Array(1, 2))
}
assert(
clue(e).getMessage.contains(
"arrays have the same elements but different reference equality. Convert the arrays to a non-Array collection if you intend to assert the two arrays have the same elements. For example, `assertEquals(a.toSeq, b.toSeq)"
)
)
}
}

0 comments on commit 0354373

Please sign in to comment.