【问题标题】:Scalatest provide position different file for assertionScalatest 为断言提供位置不同的文件
【发布时间】:2019-11-13 22:46:39
【问题描述】:

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

我的问题是我有一个父测试类和一个子测试类。子测试类在父类中使用断言方法。这会导致测试失败消息指向父方法而不是子方法。

例如,我有一个父测试类:

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

还有一个子测试类:

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

我可以提供职位吗?

【问题讨论】:

    标签: scala scalatest


    【解决方案1】:

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

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

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

    现在说说它的工作原理:

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

    【讨论】:

    • 有效!谢谢。虽然是一个小问题,我的 IDE (IntelliJ) 没有提供指向文件本身的超链接,即使文件名和行显示正确。你知道有什么解决办法吗?
    • @krisath 不,对不起
    猜你喜欢
    • 2016-10-25
    • 2014-01-26
    • 1970-01-01
    • 2014-08-26
    • 2011-01-15
    • 1970-01-01
    • 2019-03-10
    • 1970-01-01
    • 2016-05-14
    相关资源
    最近更新 更多