6
votes

Experimenting with concurrent execution I was wondering how to actually test it. The execution flow is of a side-effect nature and futures are created to wrap independent executions/processing.

Been searching for some good examples on how to properly unit test the following scenarios (foo and bar are the methods I wish to test):

scenario #1

def foo : Unit = {
    Future { doSomething }
    Future { doSomethingElse }
}

private def doSomething : Unit = serviceCall1
private def doSomethingElse : Unit = serviceCall2

Scenario motivation

foo immediately returns but invokes 2 futures which perform separate tasks (e.g. save analytics and store record to DB). These service calls can be mocked, but what I'm trying to test is that both these services are called once I wrap them in Futures

scenario #2

def bar : Unit = {
    val futureX = doAsyncX
    val futureY = doAsyncY
    for {
        x <- futureX
        y <- futureY
    } yield {
        noOp(x, y)
    }
}

Scenario motivation

Start with long running computations that can be executed concurrently (e.g. get the number of total visitors and get the frequently used User-Agent header to our web site). Combine the result in some other operation (which in this case Unit method that simply throws the values)

Note I'm familiar with actors and testing actors, but given the above code I wonder what should be the most suitable approach (refactoring included)

EDIT What I'm doing at the moment

implicit value context = ExecutionContext.fromExecutor(testExecutor)

def testExecutor = {
    new Executor {
        def execute(runnable : Runnable) = runnable.run
    }
}

This ExecutionContext implementation will not run the Future as a separate thread and the entire execution will be done in sequence. This kinda feels like a hack but based on Electric Monk answer, it seems like the other solution is more of the same.

3
I deleted my answer, since it wasn't on topic, but you should really explain your problem more clearly.Gabriele Petronella
@GabrielePetronella Thanks for the answer, and for the comment. I've edited my answer to (hopefully) better reflect my intentions.Bivas
the only thing needed to be tested is that foo makes a call on the 2 methods doSomething and doSomethingElse ? you are looking for a proof that they are called and dont care what they do ?Nimrod007
@Nimrod007 correct. Scenario #1 tests that both services are called. Scenario #2 is more complex but noOp can be a mocked services that I wish to test if it was invoked as expectedBivas
Other than switching to actually returning Futures (probably the better option), the only alternatives I see are to use a sequential executor (as you've done), or to hack your mock services mark a condition you can await in the test code.Tomer Gabel

3 Answers

2
votes

One solution would be to use a DeterministicExecutor. Not a scalaesque solution, but should so the trick.

0
votes

ScalaTest 3.x supports asynchronous non-blocking testing.