2012-02-01 39 views
5

我正在做一個簡單的代碼片段,它應該通過Box[String]與請求用戶代理傳遞給一個幫助類,該類返回應該添加到html元素的css類。我這樣做是因爲讓Lift提供一個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 _ => "" 
    } 
} 

我的問題是,我想編寫一個單元測試此類似:因爲S.requestEmpty

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>) 
    } 
    } 
} 

此測試失敗。我應該怎麼做才能爲該代碼段提供一個帶有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
,但我不知道如何才達到我的目標。

回答

3

發出請求,並在每個測試例如自動應用它,你將需要使用特質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>) 
    } 
    } 
} 
+0

優秀的,但如果是用戶代理設置?它應該添加到給予'ParamCalcInfo'的Map中嗎? – 2012-05-27 17:31:36

+0

不,Req()的第5個參數是一個HttpRequest。您應該通過所需的標題(例如,用戶代理) – 2012-05-27 17:53:03

+0

我更新了答案以顯示模擬的請求。 – 2012-05-27 18:39:27