Scala Test
Scalaでテストというと、Scala Test でしょう。いろいろなサイトで使い方が紹介されています。
Scala Testのサイトは、http://www.scalatest.org/です。
Scala Testサイトにある、Getting started with JUnit 4 and ScalaTestを参考にしてコードを書いてみます。
Scala Testを使ってテストを試すために、先ほどのhelloクラスを拡張します。
package seedo import java.util.Date import java.text._ class hello { val me = "Hello" def now : Date = { new Date } def append(str:String) : String = { me + " " + str } def isEmpty : Boolean = true }
Scala Testで書いたテストコードです。
アサーションの書き方には、JUnitスタイルと、Scala Testスタイルの2種あります。
どちらを使うかは好みです。
package test import org.scalatest.junit.AssertionsForJUnit import org.junit.Assert._ import org.junit.Test import org.junit.Before import seedo.hello class scalatestHello extends AssertionsForJUnit { var hello: hello = _ @Before def initialize() { hello = new hello } @Test def verifyEasy() { // Uses JUnit-style assertions assertEquals("Hello easy!", hello.append("easy!")) assertTrue(hello.isEmpty) try { "verbose".charAt(-1) fail() } catch { case e: StringIndexOutOfBoundsException => // Expected } } @Test def verifyFun() { // Uses ScalaTest assertions assert(hello.append("fun!") === "Hello fun!") assert(hello.isEmpty) intercept[StringIndexOutOfBoundsException] { "concise".charAt(-1) } } }
Scalaスタイル
Scalaでプログラム書くんだから、「スタイルはScalaスタイル」という人は、JUnitSuiteというクラスを使いましょう。
これを使うには、テストクラスは JUnitSuite を継承させます。
package test import org.scalatest.junit.JUnitSuite import org.junit.Assert._ import org.junit.Test import org.junit.Before import seedo.hello class scalatestHello2 extends JUnitSuite { var hello: hello = _ @Before def initialize() { hello = new hello } @Test def verifyEasy() { // Uses JUnit-style assertions assertEquals("Hello easy!", hello.append("easy!")) assertTrue(hello.isEmpty) try { "verbose".charAt(-1) fail() } catch { case e: StringIndexOutOfBoundsException => // Expected } } @Test def verifyFun() { // Uses ScalaTest assertions assert(hello.append("fun!") === "Hello fun!") assert(hello.isEmpty) intercept[StringIndexOutOfBoundsException] { "concise".charAt(-1) } } }
さらに、「===」なんてという人は、「~じゃないと」という雰囲気で書くことも。
ShouldMatchersForJUnitクラスをimportして使います。
~should be ~ というように書きます。
hello.append("fun!") should be ("Hello fun!")
package test import org.scalatest.junit.JUnitSuite import org.scalatest.junit.ShouldMatchersForJUnit import org.junit.Test import org.junit.Before import seedo.hello class scalatestHello3 extends JUnitSuite with ShouldMatchersForJUnit{ var hello: hello = _ @Before def initialize() { hello = new hello } @Test def verifyEasy() { // Uses JUnit-style assertions assert(hello.append("easy!") === "Hello easy!") assert(hello.isEmpty) try { "verbose".charAt(-1) fail() } catch { case e: StringIndexOutOfBoundsException => // Expected } } @Test def verifyFun() { // Uses ScalaTest assertions hello.append("fun!") should be ("Hello fun!") assert(hello.isEmpty) intercept[StringIndexOutOfBoundsException] { "concise".charAt(-1) } } }
このスタイルの雰囲気は西洋風でいいですね。
コメントを残す
コメントを投稿するにはログインしてください。