Scala规范单元测试

时间:2012-01-10 13:59:52

标签: unit-testing scala specifications specs specs2

我有以下课程,我想编写一些规范测试用例,但我真的很新,我不知道如何开始。我的班级喜欢这样:

class Board{

  val array = Array.fill(7)(Array.fill(6)(None:Option[Coin]))

  def move(x:Int, coin:Coin) {
    val y = array(x).indexOf(None)
    require(y >= 0) 
    array(x)(y) = Some(coin)
   }

  def apply(x: Int, y: Int):Option[Coin] = 
     if (0 <= x && x < 7 && 0 <= y && y < 6) array(x)(y)
     else None

  def winner: Option[Coin] = winner(Cross).orElse(winner(Naught))

  private def winner(coin:Coin):Option[Coin] = {
    val rows = (0 until 6).map(y => (0 until 7).map( x => apply(x,y)))
    val cols = (0 until 7).map(x => (0 until 6).map( y => apply(x,y)))
    val dia1 = (0 until 4).map(x => (0 until 6).map( y => apply(x+y,y)))
    val dia2 = (3 until 7).map(x => (0 until 6).map( y => apply(x-y,y)))

    val slice = List.fill(4)(Some(coin))
    if((rows ++ cols ++ dia1 ++ dia2).exists(_.containsSlice(slice))) 
      Some(coin)
    else None
  }  

  override def toString = {
    val string = new StringBuilder
    for(y <- 5 to 0 by -1; x <- 0 to 6){
        string.append(apply(x, y).getOrElse("_"))
        if (x == 6) string.append ("\n") 
        else string.append("|")
    }
    string.append("0 1 2 3 4 5 6\n").toString
  }
}

谢谢!

2 个答案:

答案 0 :(得分:4)

我只能提出Daniel的建议,因为您最终会使用TDD来获得更实用的API。

我还认为您的应用程序可以通过混合使用specs2和ScalaCheck进行很好的测试。这里是一本规范草案,可以帮助您入门:

  import org.specs2._
  import org.scalacheck.{Arbitrary, Gen}

  class TestSpec extends Specification with ScalaCheck { def is =

    "moving a coin in a column moves the coin to the nearest empty slot" ! e1^
    "a coin wins if"                                                     ^
      "a row contains 4 consecutive coins"                               ! e2^
      "a column contains 4 consecutive coins"                            ! e3^
      "a diagonal contains 4 consecutive coins"                          ! e4^
                                                                         end

    def e1 = check { (b: Board, x: Int, c: Coin) =>
      try { b.move(x, c) } catch { case e => () }
      // either there was a coin before somewhere in that column
      // or there is now after the move
      (0 until 6).exists(y => b(x, y).isDefined)
    }

    def e2 = pending
    def e3 = pending
    def e4 = pending

    /**
     * Random data for Coins, x position and Board
     */
    implicit def arbitraryCoin: Arbitrary[Coin]     = Arbitrary { Gen.oneOf(Cross,       Naught) }
    implicit def arbitraryXPosition: Arbitrary[Int] = Arbitrary { Gen.choose(0, 6) }
    implicit def arbitraryBoardMove: Arbitrary[(Int, Coin)]   = Arbitrary {
      for {
        coin <- arbitraryCoin.arbitrary
        x    <- arbitraryXPosition.arbitrary
      } yield (x, coin)
    }
    implicit def arbitraryBoard: Arbitrary[Board]   = Arbitrary {
      for {
        moves <- Gen.listOf1(arbitraryBoardMove.arbitrary)
      } yield {
        val board = new Board
        moves.foreach { case (x, coin) => 
          try { board.move(x, coin) } catch { case e => () }}
          board
      }
    }


  }

  object Cross extends Coin {
    override def toString = "x"
  }
  object Naught extends Coin {
    override def toString = "o"
  }
  sealed trait Coin

我实现的e1属性不是真实的,因为它并没有真正检查我们是否将硬币移动到最近的空槽,这就是你的代码和你的API建议。您还需要更改生成的数据,以便生成更改xo的板。这应该是学习如何使用ScalaCheck的好方法!

答案 1 :(得分:-1)

我建议你抛出所有代码 - 好吧,把它保存到某处,但是从零开始使用TDD。

Specs2网站有很多关于如何编写测试的例子,但是使用TDD - 测试驱动设计 - 来做到这一点。事实上添加测试至少可以说是次优的。

所以,想想你想要处理最简单功能的最简单的情况,为此编写测试,看到它失败,编写代码来修复它。必要时重构,并重复下一个最简单的案例。

如果您需要有关如何进行TDD的帮助,我衷心赞同Clean Coders上有关TDD的视频。至少,请观看Bob Martin从设计到结束编写全类TDD风格的第二部分。

如果您知道如何进行一般测试,但对Scala或规格感到困惑,请更具体地说明您的问题。