0
votes

In the following ScalaTest example, obtainLock is a Java function which takes in a String and two functional interfaces for success/failure calls. This occurs in an asynchronous manner, meaning the lambdas are called from a different thread.

With the existing code, this test returns true because it exits the test block before either lambda are called. I've taken a look at the Async Testing Documentation for ScalaTest, but I'm not sure how I'd go about writing the tests since the Java functions I'm calling don't return a Future.

Is there a way to test this asynchronous code in ScalaTest? I'm using Scala 2.12, ScalaTest 0.9.6 and Java 9.

  "Acquiring locks" - {
    "Return a lock for a key with valid lease limit" in {
      locker.obtainLock(lockKeyA, suc => {
        suc.key shouldEqual "AAA"
        suc.validUntilInMs should be > System.currentTimeMillis()
      }, (fmsg, lockInfo) => {
        fmsg shouldBe ""
      })
    }
1

1 Answers

0
votes

Probably solution will be to convert to scala Future. And combine with Async* suite from your link. E.g.

sealed trait SomeResult
case class SomeFailureType(fmsg: ???, lockInfo: ???) extends SomeResult
case class SomeSuccessType(suc: ???) extends SomeResult
val p = Promise[SomeResult]

locker.obtainLock(lockKeyA, suc => {
    p.complete(SomeSuccessType(suc))
}, (fmsg, lockInfo) => {
    p.complete(SomeFailureType(fmsg, lockInfo))
})

p.future.map {
    case SomeSuccessType(suc) =>
        // assert success returning Future[Assertion]
        // e.g. suc.key shouldEqual "AAA"
    case SomeFailureType(fmsg, lockInfo) =>
        // assert failure returning Future[Assertion]
}