如何对 Numeric 的不同类型类实例进行单元测试?

How to unit-test different typeclass instances for Numeric?

假设我有两个类型类实例 Numeric

class Money(c: String, x: Long, y: Int)
class Quantity(c: String, x: Long, y: Int)
implicit val numericMoney: Numeric[Money] = new Numeric[Money]
implicit val numericQuantity: Numeric[Quantity] = new Numeric[Quantity]

Money 和 Quantity 在 Numeric 实例中的行为应该相同。 我有 scalaTest 测试来检查 Money 是否正确运行。

例如

import implicits.NumericMoney.numericMoney._

class MoneyOpsSpec extends WordSpec with Matchers {

  val max = Money("", Long.MaxValue, 999999999)
  val min = Money("", Long.MinValue, -999999999)

  "A Money object" when {
    "zero" should {
      "be neutral element under addition" in {
        zero + Money("", 15, 50) should ===(Money("", 15, 50))
        Money("", 15, 50) + zero should ===(Money("", 15, 50))
      }
      "be neutral element under subtraction" in {
        zero - Money("", 15, 50) should ===(Money("", -15, -50))
        Money("", 15, 50) - zero should ===(Money("", 15, 50))
      }
      "be invariant under negation" in {
        -zero should ===(zero)
      }
    }
  }
}

Quantity spec 应该以相同的方式执行。我可以实施通用规范并使用 MoneyQuantity 作为该规范的输入吗?或者 scalaTest 或 specs2 是否有一些东西来确保 Numeric 类型类实例的行为正确?我可以轻松切换测试框架。

我认为您需要的是创建用于测试不同操作的抽象方法,并将其用于两个对象。例如。测试加法

  def testAddition[T](a: T, b: T, expectedResult: T)(implicit n: Numeric[T]) = {
    n.plus(a, b) ==== expectedResult
  }

那么你可以用MoneyQuantity

调用这个方法
testAddition(Money(1, 1), Money(2, 2), Money(3, 3))
testAddition(Quantity(1, 1), Quantity(2, 2), Quantity(3, 3))

Can I implement a generic spec and use Money and Quantity as an input for that spec?

当然可以。只需将隐式作为构造函数参数即可。未经测试,但应该大约(变化很小):

abstract class NumOpsSpec[T](implicit num: Numeric[T], tag: ClassTag[T]) extends WordSpec with Matchers {
  import num._

  val max: T
  val min: T
  val someElement: T

  s"A ${tag.runtimeClass.simpleName} object" when {
    "zero" should {
      "be neutral element under addition" in {
        zero + someElement should ===(someElement)
        someElement + zero should ===(someElement)
      }
      "be neutral element under subtraction" in {
        zero - someElement should ===(- someElement)
        someElement - zero should ===(someElement)
      }
      "be invariant under negation" in {
        -zero should ===(zero)
      }
    }
  }
}

class MoneyOpsSpec extends NumOpsSpec[Money] {
  override val max = Money("", Long.MaxValue, 999999999)
  override val min = Money("", Long.MinValue, -999999999)
  override val someElement = Money("", 15, 50)
}

class QuantityOpsSpec extends NumOpsSpec[Quantity] {
  override val max = ???
  override val min = ???
  override val someElement = ???
}

您还可以查看 https://github.com/typelevel/discipline 以了解一般测试类型类规则。