1 scala future stub mockito akka
我正在编写测试用例来存根存储库Future函数,并抛出一个Exception模拟某些数据库错误的测试用例。
我期望 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
}
}
Run Code Online (Sandbox Code Playgroud)
这是输出:
[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
Run Code Online (Sandbox Code Playgroud)
我曾尝试替换thenReturn(Future.failed..为thenThrow(new Exception)但无法处理错误ava.lang.AssertionError: assertion failed: timeout (3 seconds) during expectMsg while waiting for
您不想将异常抛出Future.failed到 中,只需在那里创建它即可。在调用真实存储库时发生的情况是,在计算结果时抛出异常Future,然后将其捕获并放置在实例中Failure,而不是将成功的计算结果放置在实例中Success。所以:
when(repository.create(any[Team])(same(ec))).thenReturn(Future.failed(new Exception(...)))
Run Code Online (Sandbox Code Playgroud)
应该做这项工作。