Unit test code async scala

While experimenting with simultaneous execution, I was wondering how to check this. The thread of execution has a side effect, and futures are created to carry independent execution / processing.

There was a search for good examples of how to correctly use unit test the following scripts ( foo and bar ):

script # 1

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

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

Script motivation

foo returns immediately, but calls 2 futures that perform separate tasks (for example, save analytics and write a record to the database). These service calls can be mocked, but what I'm trying to check is that both of these services call as soon as I complete them in Future s

script # 2

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

Script motivation

Start with lengthy calculations that can be done at the same time (for example, get the total number of visitors and get the frequently used User-Agent header on our website). Combine the result in some other operation (which in this case is the Unit method, which simply returns the values)

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

EDIT What am I doing right now

  implicit value context = ExecutionContext.fromExecutor (testExecutor)

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

This implementation of ExecutionContext does not start Future as a separate thread, and all execution will be executed sequentially. This view looks like a hack, but based on Electric Monk's answer, it looks like the other solution is more similar.

+6
source share
3 answers

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

+2
source

ScalaTest 3.x supports asynchronous non-blocking testing.

0
source

Source: https://habr.com/ru/post/973453/


All Articles