加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

单元测试 – Scala测试嘲笑隐含参数?

发布时间:2020-12-16 09:11:52 所属栏目:安全 来源:网络整理
导读:当涉及隐含参数时,我有一段艰难的时刻想了解如何在 Scala中编写测试. 我有以下(简短版本)我的代码和测试: 实施(Scala 2.10,Spray和Akka): import spray.httpx.SprayJsonSupport._import com.acme.ResultJsonFormat._case class PerRequestIndexingActor(ct
当涉及隐含参数时,我有一段艰难的时刻想了解如何在 Scala中编写测试.

我有以下(简短版本)我的代码和测试:

实施(Scala 2.10,Spray和Akka):

import spray.httpx.SprayJsonSupport._
import com.acme.ResultJsonFormat._

case class PerRequestIndexingActor(ctx: RequestContext) extends Actor with ActorLogging {
  def receive = LoggingReceive {
    case AddToIndexRequestCompleted(result) =>
      ctx.complete(result)
      context.stop(self)
  }
}


object ResultJsonFormat extends DefaultJsonProtocol {
  implicit val resultFormat = jsonFormat2(Result)
}

case class Result(code: Int,message: String)

测试(使用ScalaTest和Mockito):

"Per Request Indexing Actor" should {
    "send the HTTP Response when AddToIndexRequestCompleted message is received" in {
      val request = mock[RequestContext]
      val result = mock[Result]

      val perRequestIndexingActor = TestActorRef(Props(new PerRequestIndexingActor(request)))
      perRequestIndexingActor ! AddToIndexRequestCompleted(result)

      verify(request).complete(result)
    }
  }

这行,verify(request).complete(result)使用隐式的Marshaller将Result转换成JSON.

我可以通过添加隐式val marshaller来引导编组:Marshaller [Result] = mock [Marshaller [Result]],但是当我运行测试时,使用了不同的Marshaller实例,因此验证失败.

即使明确地传递模拟马歇尔完成失败.

那么,任何人可以建议如何为隐式参数创建一个模拟对象,并确保该实例是使用的实例?

解决方法

这是一个完美的情况,使用Mockito的匹配器为编组者.你不应该需要嘲笑隐含的编组者.您真正想要做的是验证完成是否与匹配您期望的结果以及编组器的某些实例相匹配.首先,如果你还没有这样做,请将Mockito匹配器导入到范围内,如下所示:

import org.mockito.Matchers._

然后,如果您希望对结果进行引用匹配,则可以如下验证:

verify(request).complete(same(result))(any[classOf[Marshaller[Result]]])

或者,如果你想要等效匹配结果,你可以做:

verify(request).complete(eq(result))(any(classOf[Marshaller[Result]]))

匹配器的诀窍是,一旦你使用一个arg,你必须将它们用于所有的args,所以这就是为什么我们必须使用一个结果.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读