8

我是 Scala 和 Spec2 的新手。

我想创建以下测试,但我从编译器中得到一个错误。

这是我想写的测试

import org.specs2.mutable._
import org.specs2.specification._
import org.specs2.matcher._
import org.specs2.matcher.MatchResult

class SimpleParserSpec extends Specification {

"SimpleParser" should {

val parser = new SimpleParser()

  "work with basic tweet" in {
      val tweet = """{"id":1,"text":"foo"}"""
      parser.parse(tweet) match {
        case Some(parsed) => {
                                parsed.text must be_==("foo")
                                parsed.id must be_==(1)
                              }
        case _ =>  failure("didn't parse tweet") 
      }
    }
  }
}

我收到错误:C:\Users\haques\Documents\workspace\SBT\jsonParser\src\test\scala\com\twitter\sample\simpleSimpleParserSpec.scala:17: 找不到 org 类型的证据参数的隐式值。 specs2.execute.AsResult[对象]

问候,

绍希杜尔

4

3 回答 3

8

The compiler produces an error here because he tries to unify a MatchResult[Option[Parsed]] with a failure of type Result. They unify as Object and the compiler can't find an AsResult typeclass instance for that. You can fix your example by providing another MatchResult for the failed case:

parser.parse(tweet) match {
  case Some(parsed) => {
    parsed.text must be_==("foo")
    parsed.id must be_==(1)
  }
  case _ =>  ko("didn't parse tweet")
}

The ok and ko methods are the equivalent of success and failure but are MatchResults instead of being Results.

于 2014-08-14T00:35:38.610 回答
2

最好写成如下:

"work with basic tweet" in {
  val tweet = """{"id":1,"text":"foo"}"""
  parser.parse(tweet) aka "parsed value" must beSome.which {
    case parsed => parsed.text must_== "foo" and (
      parsed.id must_== 1)
  }
}
于 2014-08-13T16:22:26.563 回答
0

您可以尝试的一件事是使 SimpleParser 成为一个特征。在使用 Specs2 时,这通常对我来说效果更好。然后你可以调用 parse(tweet)。我还建议稍微分解测试。

class SimpleParserSpec extends Specification with SimpleParser { 
     val tweet = """{"id":1,"text":"foo"}"""
     SimpleParser should {
        "parse out the id" in {
              val parsedTweet = parse(tweet)
              parsedTweet.id === 1
         }
}

从这里您可以添加您想要测试的其他字段。

EDIT: Looking back at what I wrote, I see I didn't completely answer what you were asking. you could put the === and then failure into cases like you already had, but within the framework of what I have.

于 2014-08-13T16:29:22.643 回答