Skip to content

Instantly share code, notes, and snippets.

@rafaeldff
Created August 12, 2012 06:02
Show Gist options
  • Save rafaeldff/3330034 to your computer and use it in GitHub Desktop.
Save rafaeldff/3330034 to your computer and use it in GitHub Desktop.
A stub-centric test syntax in Scala
/** System under test */
package net.rafaelferreira
case class Street(streetName: String)
case class City(name:String)
case class Address(city:City, street:Street)
trait AddressMapper {
def map(id:String): Option[Address]
}
trait Database {
def find(table:String, id:String): Option[Map[String,String]]
}
class DatabaseBackedAddressMapper(db:Database) extends AddressMapper {
override def map(id:String): Option[Address] = {
for (address <- db.find("addresses", id);
city <- db.find("cities", address("city"));
street <- db.find("streets", address("street")))
yield Address(City(city("name")),Street(street("name")))
}
}
package net.rafaelferreira
import org.specs2.Specification
class AddressMapperSpec extends Specification with Goose {
val id = dep[String]
val database = dep[Database]
def is = check(new DatabaseBackedAddressMapper(database()).map(id())) {
_.when(id ==> "123").
and(database.stub(_.find("addresses", "123")) ==> Some(Map("city" -> "789", "street" -> "999"))).
and(database.stub(_.find("cities", "789")) ==> Some(Map("name" -> "Curitiba"))).
but {
_.when(database.stub(_.find("streets", "999")) ==> None).
then(_ must_== None)
}.
but {
_.when(database.stub(_.find("streets", "999")) ==> Some(Map("name" -> "St. st."))).
then(_ must_== Some(Address(City("Curitiba"), Street("St. st."))))
}
}
}
@rafaeldff
Copy link
Author

So far I have this syntax working, but the test reporting is tricky. I'm now looking into how to abuse Specs2' auto-examples feature.

@rafaeldff
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment