Sunday, December 27, 2015

NullPointer Exception while testing with Scala Futures...

So I was trying to unit testing Scala Futures, and I was getting NullPointerException out of nowhere. I was frustrated since the stacktrace didn't much more information, not a minimal clue of what was missing. It was until I payed attention to some other examples when I realized that I was missing something important:
import ExecutionContext.Implicits.global
I do not know why it wasn't detected at compile time, or why the exception was only coming as NullPointerException without any other hint. My test is something like this:

"Some test" should {
    "execute this" in {   
      val client = mock[AClass]
      val host = new BClass(client) 
      doReturn(Future {x}).when(client).aMethod(any[String], any[String]) // This was throwing a NPE
      val response = host.anyMethod(cI, mA, bL)
      Await.result(response, Duration(30, SECONDS)) 
      there was one(client). aMethod(any[String], any[String])
    }
  }