Home > database >  Have assertion error return respective list position instead of the object?
Have assertion error return respective list position instead of the object?

Time:09-28

test("Comparison") {
  val list: List[String] = List("Thing", "Entity", "Variable")
  val expected: List[String] = List("Thingg", "Entityy", "Variablee")
  var expectedPosition = 0
  for (item <- list) {
    assert(list(expectedPosition) == expected(expectedPosition))
    expectedPosition  = 1
  }
}

In Scala, in order to make my low-level code tests more readable, I thought it would be a good idea to just use one assertion and have it iterate through a loop and increase an accumulator at the end. This is to test more than one input at a time when the multiple inputs would more or less have similar attributes. When the assertion fails, it comes back as "Thing[]" did not equal "Thing[g]". Instead of it reporting the item in the list that failed, is there a way to get it to directly state the list position without concatenating the list position before the assertion or using a conditional statement that returns the list position? Like I would rather keep it all contained within the assert() error report.

CodePudding user response:

val expected: LazyList[String] = ...

expected.zip(list)
        .zipWithIndex
        .foreach{case ((exp,itm),idx) =>
          assert(exp == itm, s"off at index $idx")
        }

//java.lang.AssertionError: assertion failed: off at index 0

expected is lazy so that it is traversed only once even though it gets zipped twice.

  • Related