Skip to content

Instantly share code, notes, and snippets.

@lucmolinari
Last active September 24, 2018 20:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save lucmolinari/a068736e76d763c1fc138a80fd2d030b to your computer and use it in GitHub Desktop.
Save lucmolinari/a068736e76d763c1fc138a80fd2d030b to your computer and use it in GitHub Desktop.
Testing Future Objects with ScalaTest - More details at http://lucianomolinari.com/2016/08/07/testing-future-objects-scalatest/
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
object HelloWorld {
val theOneWhoCannotBeNamed = "Voldemort"
def sayHelloTo(name: String): Future[Option[String]] = {
Future {
if (theOneWhoCannotBeNamed.equals(name)) None else Some(getHelloMessage(name))
}
}
def getHelloMessage(name: String): String = {
s"Hello ${name}, welcome to the future world!"
}
}
import org.scalatest.{AsyncFunSuite, Matchers}
class HelloWorldAsyncSpec extends AsyncFunSuite with Matchers {
test("A valid message should be returned to a valid name") {
HelloWorld.sayHelloTo("Harry") map { result =>
result shouldBe Some("Hello Harry, welcome to the future world!")
}
}
test("No message should be returned to the one who cannot be named") {
HelloWorld.sayHelloTo("Voldemort") map { result =>
result shouldBe None
}
}
}
import org.scalatest.{FunSuite, Matchers}
import scala.concurrent.Await
import scala.concurrent.duration._
class HelloWorldSpecWithAwait extends FunSuite with Matchers {
test("A valid message should be returned to a valid name") {
val result = Await.result(HelloWorld.sayHelloTo("Harry"), 500 millis)
result shouldBe Some("Hello Harry, welcome to the future world!")
}
test("No message should be returned to the one who cannot be named") {
val result = Await.result(HelloWorld.sayHelloTo("Voldemort"), 500 millis)
result shouldBe None
}
}
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.{FunSuite, Matchers}
class HelloWorldSpecWithScalaFutures extends FunSuite with Matchers with ScalaFutures {
test("A valid message should be returned to a valid name") {
whenReady(HelloWorld.sayHelloTo("Harry")) { result =>
result shouldBe Some("Hello Harry, welcome to the future world!")
}
}
test("No message should be returned to the one who cannot be named") {
whenReady(HelloWorld.sayHelloTo("Voldemort")) { result =>
result shouldBe None
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment