【问题标题】:Scala / Lift: How do I write unit tests that test a snippet's response to different parametersScala / Lift:如何编写单元测试来测试片段对不同参数的响应
【发布时间】:2012-02-03 07:22:32
【问题描述】:

我正在尝试编写一个 Specs2 测试,该测试将测试 sn-p 的输出以响应通常从模板传入的不同参数,但我无法弄清楚如何去做。

例如,在这个 div 中使用 sn-p 标注:

<div class="lift:Snippet.method?param1=foo"></div>

我将参数 param1 传递给 sn-p。我的 sn-p 看起来像这样:

class Snippet {
  def method(in:NodeSeq):NodeSeq = {
    val param1 = S.attr("param1") openOr ""
    param1 match {
      case "foo" => //do something
      case "bar" => //do something else
      case _ => //do yet another thing
    }
  }
}

所以在我的测试中,我想测试 sn-p 如何响应不同的 param1 值

class SnippetTest extends Specification {
  "Snippet" should {
    "do something" in {
      val html = <ul>
          <li class="first">
          <li class="second">
          <li class="third">
        </ul>

      //I need to set param1 here somehow
      val out = Snippet.method(html)
      //then check that it did what it was supposed to
      out.something must be "xyz"
    }
  }
}

如何设置 param1?

我是一个大时代的 scala 和提升 newb(来自 python+django),所以如果我叫错了树,请引导我到正确的树。我想可能是这样,我整天都在谷歌上搜索,没有发现任何与这个问题很相似的问题。

谢谢,

布莱克

【问题讨论】:

    标签: scala lift


    【解决方案1】:

    好的,我已经弄清楚了。这个问题没有引起太大的兴趣,但如果有人在谷歌上搜索同样的问题/问题,你可以这样做:

    Lift 的“S”对象需要添加我们的任意属性,以便在被询问时为我们的 sn-p 提供我们想要测试的属性。不幸的是,有两个问题。首先,“S”对象仅在收到http请求时才被初始化。其次,S.attr 是不可变的。

    Lift 有一个名为 mockweb 的包,它允许您发出模拟 http 请求。这个包的文档通常讨论测试会话和用户登录等等,但它也提供了初始化“S”作为规范测试一部分的机制。

    第一个问题,初始化 S,通过将我们的测试类定义为 WebSpec 的扩展而不是 Specification(WebSpec 是 mockweb 包的一部分并扩展 Specification),并在规范定义期间调用“withSFor”来解决,这将初始化“S”

    第二个问题,处理 S.attr 是不可变的,通过“S”方法“withAttrs”解决。 “withAttrs”执行您提供的代码块,其中包含常规属性和您在地图中提供的属性。您的任意属性只能从 S.attr 临时获得

    这是我原来的问题的测试,经过修改以解决两个问题:

    import net.liftweb.mockweb._
    
    class SnippetTest extends WebSpec {
      "Snippet" should {
        "do something" withSFor("/") in {
          val html = <ul>
              <li class="first">
              <li class="second">
              <li class="third">
            </ul>
    
          //here I set param1
          var m = new HashMap[String, String]
          m += "param1" -> "foo"
    
          val s = new Snippet()
    
          //then tell S to execute this block of code
          //with my arbitrary attributes.
          //'out' will be the NodeSeq returned by s.method
          val out = S.withAttrs(S.mapToAttrs(m)){
            s.method(html)
          }
    
          //then check that it did what it was supposed to
          out.something must be "xyz"
        }
      }
    }
    

    编辑:清晰度

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-10
    • 2018-12-15
    • 2015-01-16
    • 2012-02-03
    • 2019-01-28
    • 1970-01-01
    • 2013-12-05
    相关资源
    最近更新 更多