vendredi 6 mars 2020

Scala avoid Thread sleep for asynchronous test cases

I'm writing unit tests for a method that runs a primary function and then logs details about the request asynchronously.

def someMethod(data: Object): SomeType =
  for {
    result <- someOtherMethod(data).withLogging(logMethod)
  }

The method logMethod is an async task. In my tests, I want to ensure that the logger is receiving a message, however, the thread completes too soon at times making the test flaky and causing an Unsatisfied result sometimes.

Example test case:

it("logs an error if an upload was attempted with some failure case") {
  val uploadData = someData

  mockSomeCall()

  mockAnotherCall()

  testController.methodWeAreTesting(uploadData).shouldBeRight()

  Thread.sleep(75)

  (stubLogger
    .warn(_: RichMsg, _: Throwable, _: AnyId)(_: () => SourceLocation))
    .verify(where { (msg: RichMsg, _, _, _) =>
      msg.toString.equals(s"Some specific message")
     })
}

I'm not enjoying adding a Thread.sleep every time I need to ensure that the logger is receiving a specific message. I'd like to be able to possibly wrap the stubLogger expectation.

Let me know if more information is needed.

Aucun commentaire:

Enregistrer un commentaire