vicaba
vicaba

Reputation: 2878

Scalatest and scalamock, tests not passing when Futures are involved

I am new to scalatest and scalamock, but I've managed to write some tests. However, when a use Futures in my tests (mocking returning results and in classes themselves), tests don't seem to pass.

I've written a minimal working example hosted on github. There are two branches, "master" involves futures and "withNoFutures" doesn't.

I've executed the tests on both branches several times and the tests in "master" pass sometimes, the tests in "withNoFutures" always pass. Can anyone help me to get the tests with futures pass?

Github repo: https://github.com/vicaba/scalatestNotWorking/tree/master

The failing testing code looks like:

package example

import org.scalamock.scalatest.MockFactory
import org.scalatest.{BeforeAndAfter, FunSuite}

import scala.concurrent.Future


class SomeServiceTest extends FunSuite with BeforeAndAfter with MockFactory {

  var otherService: SomeOtherService = _

  var service: SomeService = _

  before {
    otherService = mock[SomeOtherService]
    service = mock[SomeService]
  }

  after {
    otherService = null
    service = null
  }

  test("a first test works") {
    otherService.execute _ expects() once()
    service.execute _ expects(*) returning Future.successful(true) once()
    SomeService.execute(service, otherService)
  }


  // Why this test does not work?
  test("a second test works") {
    // Copy paste the code in the first test
  }

}

If I change the code to return only a boolean (changing the corresponding implemented classes), all works fine. Otherwise the result is undeterministic

Upvotes: 1

Views: 991

Answers (1)

Yony Yatsun
Yony Yatsun

Reputation: 153

The one way to do so is to wait for result or ready(if feature may fail) and then run your code (assert/shouldBe/etc.)

import scala.concurrent.Await
import scala.concurrent.duration._

//res0 is of type Future[T]
val res0 = Await.ready(firstFeature, FiniteDuration(1,SECONDS))
//res1 is of type T (from Future[T])
val res1 = Await.result(secondFeature, FiniteDuration(1,SECONDS))

Another way is to use ScalaFuture in ScalaTest 2.0 here

Upvotes: 1

Related Questions