【问题标题】:Ambiguous implicit conversions causing compile failure in Scalatest and Argonaut.io在 Scalatest 和 Argonaut.io 中导致编译失败的模糊隐式转换
【发布时间】:2014-08-25 00:00:06
【问题描述】:

我目前正在做最崇高的编程工作,为 Json 编码/解码编写测试。我将Argonaut.io 用于Json,将Scalatest 用于我的测试框架。在 scalatest 下,在断言验证期间使用 === 会在发生故障时提供额外信息,而使用 ==simply 会给出 org.scalatest.exceptions.TestFailedException was thrown.。但是,scala 编译器并不高兴。代码如下:

val default = new Broadcast("default", "default", "default")
test("Should parse out network when present") {
  val hcursor = testHCursor(jsonPath + "complete-broadcast.json")
  val actualNetwork = Parser.BroadcastDecodeJson(hcursor)
    .getOr(default)
    .network
  assert(actualNetwork === "ESPNU")
}

这吐出了这个:

[info] Compiling 1 Scala source to /home/vagrant/waltercamp/waltercamp-dataservice/target/scala-2.10/test-classes...
[error] /home/vagrant/waltercamp/waltercamp-dataservice/src/test/scala/io/ptx/waltercamp/schedules/BroadcastParserSuite.scala:16: type mismatch;
[error]  found   : actualNetwork.type (with underlying type String)
[error]  required: ?{def ===(x$1: ? >: String("ESPNU")): ?}
[error] Note that implicit conversions are not applicable because they are ambiguous:
[error]  both method ToEqualOps in trait ToEqualOps of type [F](v: F)(implicit F0: scalaz.Equal[F])scalaz.syntax.EqualOps[F]
[error]  and method convertToEqualizer in trait Assertions of type (left: Any)BroadcastParserSuite.this.Equalizer
[error]  are possible conversion functions from actualNetwork.type to ?{def ===(x$1: ? >: String("ESPNU")): ?}
[error]     assert(actualNetwork === "ESPNU")
[error]            ^
[error] one error found
[error] (test:compile) Compilation failed

使用== 但是提供了干净的编译和传递。有没有办法向编译器提供关于使用哪种转换或转换顺序的提示?

【问题讨论】:

  • 我想说 Travis Brown 的答案是正确的,只是想指出,如果您使用 ScalaTest 2.2.0 或更高版本,即使仅使用“=”,您也会获得有关失败的更多信息=" 在你的断言中。所以这可能是首先避免问题的一种方法。

标签: scala scalaz scalatest


【解决方案1】:

我会在这里使用 ScalaTest 的版本。一种方法是显式应用转换:

assert(convertToEqualizer(actualNetwork) === "ESPNU")

但是,如果您在一个文件中多次使用 ===,这有点令人不快,并且会涉及大量重复的样板文件。另一种方法是从一般导入中排除 Scalaz 转换:

import scalaz._, Scalaz.{ ToEqualOps => _, _ }

您也可以切换到 Scalaz 的点菜导入,只要确保您不要通过 scala.syntax.equal._ 拉入 ToEqualOps。我承认我发现点菜导入有时很难维护,但如果您在测试中没有对 Scalaz 做太多事情,这也不会太糟糕。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-16
    • 1970-01-01
    相关资源
    最近更新 更多