【问题标题】:Have assertion error return respective list position instead of the object?断言错误是否返回相应的列表位置而不是对象?
【发布时间】:2021-11-19 23:57:18
【问题描述】:
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
  }
}

在 Scala 中,为了使我的低级代码测试更具可读性,我认为只使用一个断言并让它遍历一个循环并在最后增加一个累加器是一个好主意。 这是为了在多个输入或多或少具有相似属性的情况下一次测试多个输入。当断言失败时,它会返回为“Thing[]”不等于“Thing[g]”。与其报告列表中失败的项目,有没有办法让它直接声明列表位置而不在断言之前连接列表位置或使用返回列表位置的条件语句?就像我宁愿将它全部包含在 assert() 错误报告中一样。

【问题讨论】:

  • assert 采用可选字符串参数,您可以在其中包含其他信息

标签: scala unit-testing automated-tests


【解决方案1】:
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 是惰性的,即使它被压缩了两次,它也只会被遍历一次。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-05
    • 1970-01-01
    • 2021-09-18
    相关资源
    最近更新 更多