Scalatest 为断言提供位置不同的文件

Scalatest provide position different file for assertion

如何向 org.scalatest.Assertions.assert 提供 Position 以便它报告不同的位置而不是默认位置?

我的问题是我有一个 parent 测试 class 和一个 child 测试 class。 child 测试 class 使用了 parent 中的断言方法。这会导致测试失败消息指向 parent 方法而不是 child 方法。

例如,我有一个 parent 测试 class 为:

abstract class ParentSpec[A <: TestSubject] extends FunSuite {
  protected def checkId(underTest: => A, expectedId: Int): Assertion = {
    assert(underTest.id == expectedId)
  }
}

和 child 测试 class 为:

class FooSpec extends ParentSpec[Foo] {
  test("check id") {
    checkId(Foo(1, 2, 3), 999) // this fails
  }
}

如果测试失败,则断言报告问题来自 ParentSpec.scala。我怎样才能将其更改为 FooSpec.scala?

我注意到 assert 接受了一个隐含的 Position

def assert(condition: Boolean)(implicit prettifier: Prettifier, pos: source.Position): Assertion

我能以某种方式提供职位吗?

只需让 checkId 方法也接受一个隐式位置:

protected def checkId(underTest: => A, expectedId: Int)(implicit pos: Position): Assertion

就是这样。现在消息应该指向 checkId 的调用(除非它是从另一个具有自己的位置参数的函数调用的)。

现在简单介绍一下它是如何工作的:

都是基于where the compiler looks for implicitscheckId 中的 assert 调用需要隐式 Position。如果 checkId 本身接受一个隐含的 Position 参数,该参数将简单地传递给 assert。但是当这个参数不存在时,编译器将回退到 Position.here(在 Position 伴生对象中定义)。这个东西是一个宏,具体化了调用的位置。