Unit testing your Lift Mapper code.
We're all looking forward to Tim Perrett's Lift in Action book, but until Chapter 6, Testing, is done the main resource for testing in Lift is Vassil Dichev's blog post and the entry in the Lift wiki. If all you need to do is test Mapper, though, an in-memory database works just fine.
Here's what we've used:
$ cat InMemoryDB.scala
package com.spiralarm.model
import net.liftweb.mapper._
import net.liftweb.common._
import net.liftweb.util._
import java.sql._
object InMemoryDB {
val vendor = new StandardDBVendor("org.h2.Driver",
"jdbc:h2:mem:lift;DB_CLOSE_DELAY=-1", Empty, Empty)
Logger.setup = Full(net.liftweb.util.LoggingAutoConfigurer())
Logger.setup.foreach { _.apply() }
def init {
DB.defineConnectionManager(DefaultConnectionIdentifier, vendor)
Schemifier.destroyTables_!!(Schemifier.infoF _, Your, Classes, Here)
Schemifier.schemify(true, Schemifier.infoF _, Your, Classes, Here)
}
def shutdown {
// TODO: figure out if anything goes here
}
}
Effectively we create an in-memory H2 database, and use Schemifier to drop our tables and recreate them with no data. You can use something like the above in tests pretty easily...
import org.specs._
import org.specs.matcher._
import net.liftweb.mapper._
import com.spiralarm.model._
class MyTest extends SpecificationWithJUnit {
"My thing" should {
"store stuff in the database" {
InMemoryDB.init
var person = Person.create.first("Billy").last("NoMates").saveMe
var friends = Friends.find(By(Friends.person, person))
friends must_== Empty
}
}
}
...or something like that, with a less fake example that actually compiles. If you're doing a lot of this, you may want to have the in-memory initialized (and possibly shutdown) automatically around each test, and generalize to pass in the classes you care about to be Schemifier-ed. But you get the idea.


