使用scalamock返回Try [T]的mocking方法

时间:2014-11-19 21:00:07

标签: scala unit-testing mocking scalatest

我知道这可能会遗漏一些非常明显的东西,但我似乎无法模拟出一个返回Try [T]的方法

简化示例:

case class User (first: String, last: String)

// ...

// in Repository class:
  def update[T](id: Int): Try[T] = { ... }

// ...

// in scalatest test using scalamock:
test("a bad id should return a failed update") {
  val mockRepo = mock[Repository]
  (mockRepo.update[User] _).expects(13).returns(???)

  val result = mockRepo.update[User](13)
  result.isSuccess should be (false)
}

如何从模拟方法返回失败的Try [T]?

1 个答案:

答案 0 :(得分:5)

示例中T绑定到User,因此返回User失败:

(mockRepo.update[User] _).expects(13).returns(Failure[User](new Exception("Failed!")))