在Lift中测试一个片段

时间:2012-02-01 20:55:42

标签: scala testing lift

我正在创建一个简单的代码段,它应该将带有请求user-agent的Box[String]传递给一个helper类,该类传递应该添加到html元素的css类。我这样做是因为让Elev提供html响应与html5boilerplate中的条件注释似乎很棘手。这就是我现在所拥有的并且有效:

class LiftBoilerplate {

   def render = "html [class+]" #> getClassForUserAgent(S.request)

   private def getClassForUserAgent(request:Box[Req]) = request match {
       case Full(r) => LiftBoilerplateHelper.getHtmlClass(r.userAgent)
       case _ => ""
   }
}

我的问题是我想为此编写单元测试:

object LiftBoilerplateSpecs extends Specification {

  val session = new LiftSession("", randomString(20), Empty)

  "LiftBoilerplate" should {
    "add 'no-js' to the class of an html tag element" in {

      val snippet = new LiftBoilerplate
      val result = snippet.render(<html><head></head><body>test</body></html>)

      result must ==/(<html class="no-js"><head></head><body>test</body></html>)
    }
  }
}

此测试失败,因为S.requestEmpty。我该怎么做才能为代码段提供一个带有userAgent的模拟请求?

到目前为止,我已查看http://www.assembla.com/spaces/liftweb/wiki/Unit_Testing_Snippets_With_A_Logged_In_User
http://www.assembla.com/spaces/liftweb/wiki/Mocking_HTTP_Requests
但我不明白如何实现我的目标。

1 个答案:

答案 0 :(得分:3)

要发出请求并在每个测试示例中自动应用它,您需要使用Trait AroundExample将每个测试包装在S.init调用中:

object LiftBoilerplateSpecs extends Specification with AroundExample {

  val session = new LiftSession("", randomString(20), Empty)

  def makeReq = {
    val mockRequest = new MockHttpServletRequest("http://localhost")
    mockRequest.headers = Map("User-Agent" -> List("Safari"))

    new Req(Req.NilPath, "", GetRequest, Empty, new HTTPRequestServlet(mockRequest, null),
      System.nanoTime, System.nanoTime, false,
      () => ParamCalcInfo(Nil, Map(), Nil, Empty), Map())
  }

  def around[T <% Result](t: => T) = S.init(makeReq, session)(t)

  "LiftBoilerplate" should {
    "add 'no-js' to the class of an html tag element" in {

      val snippet = new LiftBoilerplate
      val result = snippet.render(<html><head></head><body>test</body></html>)

      result must ==/(<html class="no-js"><head></head><body>test</body></html>)
    }
  }
}