Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用scalamock返回Try[T]的模拟方法_Scala_Unit Testing_Mocking_Scalatest - Fatal编程技术网

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

使用scalamock返回Try[T]的模拟方法,scala,unit-testing,mocking,scalatest,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 fai

我知道这可能遗漏了一些非常明显的东西,但我似乎无法模拟一个返回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]?

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

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

在您的示例中,
T
绑定到
User
,因此返回
User
故障:

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