[英][Scala][Mokito] How to stub a Future function to throw exception
我正在編寫用於對存儲庫進行存根的測試用例, Future
函數將引發Exception
以模擬某些DB錯誤。
我期望Repository.create拋出數據庫異常,它將由Actor .recover{}
處理。 但這會引發異常,並且無法被.recover
捕獲
// test
it should "return NOT created message if exception thrown" in {
val repository = mock[Repository]
val service = TestActorRef(props(repository))
implicit val ec: ExecutionContext = service.dispatcher
val mockTeam = mock[Team]
when(repository.create(any[Team])(same(ec))).thenReturn(Future.failed(throw new Exception))
service ! CreateTeam(mockTeam)
expectMsg(TeamNotCreated())
}
// service == actor
override def receive = {
case CreateTeam(team) => createTeam(team)
.recover {
case error: Exception => TeamNotCreated()
}.pipeTo(sender())
}
private def createTeam(team: Team)
: Future[TeamCreateEvent] = {
for {
newTeam <- repository.create(team = team)
} yield {
if (newTeam isDefined) TeamCreated(newTeam)
else TeamNotCreated()
}
}
// repository
override def create(team: TeamEntity)(implicit ec: ExecutionContext)
: Future[Option[TeamEntity]] = {
Future {
val column = Team.column
/**** I want to simulate some exception was thrown here ***/
val newId = Team.createWithNamedValues(
column.name -> team.name
)
if (newId.isValidLong) Option(team.copy(id = newId)) else None
}
}
這是輸出:
[info] - should return NOT created message if exception thrown *** FAILED ***
[info] java.lang.Exception:
should return updated message if collaborator team create success *** FAILED ***
[info] org.mockito.exceptions.misusing.UnfinishedStubbingException:
Unfinished stubbing detected here:
.g. thenReturn() may be missing.
[info] Examples of correct stubbing:
[info] when(mock.isOk()).thenReturn(true);
[info] when(mock.isOk()).thenThrow(exception);
[info] doThrow(exception).when(mock).someVoidMethod();
[info] Hints:
[info] 1. missing thenReturn()
[info] 2. you are trying to stub a final method, you naughty developer!
[info] 3: you are stubbing the behaviour of another mock inside before 'thenReturn' instruction if completed
我試圖用thenThrow(new Exception)
替換thenReturn(Future.failed..
thenThrow(new Exception)
但無法處理錯誤ava.lang.AssertionError: assertion failed: timeout (3 seconds) during expectMsg while waiting for
您不想將Exception 拋出到Future.failed
內部,只需在其中創建它即可。 調用真實存儲庫時發生的情況是,在計算 Future
的結果時引發了異常,然后將其捕獲並放置在Failure
實例中,而不是將成功的計算結果放置在Success
實例中。 所以:
when(repository.create(any[Team])(same(ec))).thenReturn(Future.failed(new Exception(...)))
應該做的工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.