mercredi 18 avril 2018

Testing event submission into a service

I'm testing a service implementation which performs some asynchronous computation. Here is the trait

trait Event
trait Service{
    def processEvents(ex: Seq[Event])
}

I have the following implementation:

//Business logic
trait EventHandler{
     def handleEvent(e: Event)
}

//Threading
class AsynchronousService(private final val handler: EventHandler)
     extends Service {
     def processEvents(ex: Seq[Event]) = {
        //execute handler.handleEvent(e) in some 
        //thread pool or so...
        //should not do any processing in case of ex.isEmpty
     }
}

The problem I encountered is when testing the AsynchronousService for empty Seq[Event]. Here is my test in scalatest:

it("should verify no processing in case of empty event seq"){
    val mockedHandler = //mock with Mockito
    val service = new AsynchronousService(mockedHandler)
    service.processEvents(Seq())
    Thread.sleep(1000) //<--- waiting some time. looks ugly
    verifyZeroInteraction(mockedHandler)
}

The problem is with Thread.sleep(1000). As long as the AsynchronousService perform scheduling/submission/or something else to another thread it would be incorrect to conclude without waiting some time and then perform verifyZeroInteraction(mockedHandler). But Thread.sleep(1000) looks weird.

QUESTION: Is there Scalatest facility for that maybe? Or how to write such a test correctly?

Aucun commentaire:

Enregistrer un commentaire