scala - How do I verify mockito calls in asynchronous methods -


i'm writing highly asynchronous bit of code , i'm having problems testing using specs2 , mockito. problem matchers executed before asynchronous code executes. see specs2 has await , eventually helpers - promising i'm not sure how use them.

below stripped down example illustrates problem

sut

package example.jt  import scala.concurrent._ import executioncontext.implicits.global import scala.util.{try, success, failure}  trait service {   def foo    def bar    def baz  }  class anothertest(svc: service) {    def method(fail: boolean) {     svc.baz     future {       thread.sleep(3000)       pvt(fail) oncomplete {         case success(_) => svc.foo         case failure(ex) => svc.bar       }        }      }    private def pvt(fail: boolean):future[unit] = {      val p = promise[unit]      future {       thread.sleep(2000)       if (fail) p failure (new runtimeexception("failure"))       else p success ()     }         return p.future   } } 

specs2 test

package example.jt.test  import example.jt._ import org.specs2.specification._ import org.specs2.mutable._ import org.specs2.specification._ import org.specs2.mutable._ import org.specs2.mock._  class testpromise extends specification mockito {    "mocks in promises" should {     "verify foo" in {       val svc = mock[service]       val sut = new anothertest(svc)        sut.method(false)       there one(svc).baz       there one(svc).foo       there no(svc).bar     }         "verify bar" in {       val svc = mock[service]       val sut = new anothertest(svc)        sut.method(true)       there one(svc).baz       there one(svc).bar       there no(svc).foo     }   } } 

you need wait on future calls. either using await directly:

import scala.concurrent._ import scala.concurrent.duration._  await(sut.method(false), 10 seconds) 

or using .await on matcher (look await in matchers guide):

sut.method(false) must not(throwan[exception]).await 

Comments

Popular posts from this blog

java - Intellij Synchronizing output directories .. -

git - Initial Commit: "fatal: could not create leading directories of ..." -