【问题标题】:Scala stub class with generics具有泛型的 Scala 存根类
【发布时间】:2021-08-22 22:43:40
【问题描述】:

我正在尝试对结构类似于以下代码的案例类进行存根。

case class Employee[T](name:T) {
  def greet(str:String):String = {
    "Hi, "+ str + ":" + name
  }

  def farewell(str:String):String = {
    "Bye, "+ str + ":" + name
  }
}

但是,当创建这样的存根时: val emp = stub[Employee[String]], 给出以下错误:

type mismatch;
 found   : T
 required: String
  val emp = stub[Employee[String]]

我如何存根这个类。

【问题讨论】:

    标签: scala generics scalatest


    【解决方案1】:

    通常会避免使用 Stubing case 类,但假设您使用的是 ScalaMock,请先尝试使用一些默认值对其进行扩展,例如

    class StrEmployee extends Employee[String](null)
    val emp = stub[StrEmployee]
    (emp.greet _).when("aa").returns("bb")
    assert(emp.greet("aa") == "bb")
    

    【讨论】:

      猜你喜欢
      • 2015-07-09
      • 2020-03-27
      • 2018-10-23
      • 1970-01-01
      • 2019-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-14
      相关资源
      最近更新 更多