Fortunately in the latest release of ScalaTest they have added something to do just that: the ScalaFutures trait
Say you have a class that returns a Future, e.g:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ClassThatReturnsFutures() { | |
def goDoSomething() : Future[String] = { | |
future { | |
println("I best do this asynchronously") | |
"The result" | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
test("Test a asynchronous method synchronously") { | |
val underTest = new ClassThatReturnsFutures() | |
val futureResult = underTest.goDoSomething() | |
futureResult onComplete { | |
case Success(value) => value should equal("Something") | |
case Failure(exp) => fail(exp) | |
} | |
} |
This won't work in a test as the test will finish before the future completes and the assertions are on a different thread.
ScalaFutures to the rescue! Upgrade to ScalaTest 2.0+ and mix in the ScalaFutures trait. Now you can test using whenReady:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
test("Test a asynchronous method synchronously - whenReady") { | |
val underTest = new ClassThatReturnsFutures() | |
val futureResult = underTest.goDoSomething() | |
whenReady(futureResult) { result => | |
result should equal("The result") | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
test("Test a asynchronous method synchronously - futureResult") { | |
val underTest = new ClassThatReturnsFutures() | |
val futureResult = underTest.goDoSomething() | |
futureResult.futureValue should equal("The result") | |
} |
1 comment:
Great post - you explained simply what other resources (and 4 hours of researching them) couldn't... which why this page is now in my bookmarks. Thanks!
Post a Comment