title: How do I mock a future's onComplete method?
body: <p>I have an Akka actor that works with a message containing a future. Here is a simplified version of it:</p>
  
  <pre><code>case class MyMessage(s: Future[String])
  
  class MyWorker extends Actor {
    override def receive: Receive = {
      case MyMessage(future) =&gt;
        future onComplete {
          case Success(s) =&gt; sender ! s
          case Failure(e) =&gt; throw e
        }
    }
  }
  </code></pre>
  
  <p>I am using TestActorRef to test it in specs2, but when I write a spec like this:</p>
  
  <pre><code>class MyWorkerSpec extends Specification with Mockito {
  
    val worker = TestActorRef(new MyWorker)
  
    "MyMessage" should {
  
      "return the string from a successful result" in {
        val message = MyMessage(Future("test"))
        val result = worker ? message
        result.value.get must_== Success("test")
      }
  
    }
  }
  </code></pre>
  
  <p>...then it fails with <code>NoSuchElementException: None.get</code>, and the Akka system complains about dead letters.</p>
  
  <p>Figuring that this is probably because it isn't waiting for the future to complete, I decided to try mocking the future and stubbing the <code>onSuccess</code> method. I'm not sure how to do this, though, because the <code>func</code> argument is evidently an <code>Any</code>.</p>
  
  <pre><code>class MyWorkerSpec extends Specification with Mockito {
  
    val worker = TestActorRef(new MyWorker)
  
    "MyMessage" should {
  
      "return the string from a successful result" in {
        val mockFuture = mock[Future[String]]
        mockFuture.onComplete(any[Try[String] =&gt; String]) answers {
          func =&gt; {
            func(Success("test"))
          }
        }
        worker ! MyMessage(mockFuture)
      }
    }
  }
  </code></pre>
  
  <p>How does one mock a future like this? Or is there a better way to do it?</p>