2

単体テストに Scala を使い始めたばかりで、Scala で例外がどのように処理されるかについて完全に混乱しています。以下は、JUnit テストの例です。

class Test {
  @Test
  void someTest {
    try {
      //Something
    } catch(Exception e) {
      Assert.assertTrue(e.getCause() instanceOf IOException);
    }
  }
} 

今私はScalaで同じことをしたい、私は試しました

class Test {
  @Test def someTest {
    try {
      //Something
    } catch {
      case e: Exception => assertTrue(e.getCause().isInstanceOf[IOException])
    }
  }
}

しかし、私のIDEはそれを不平を言い続けていMethod Apply is not a member of type Anyます。Scala での例外処理について読んだところ、パターン マッチャーを使用する必要があり、Scala には例外処理がないことがわかりました。これはどのように機能しますか?

4

1 に答える 1

4

scala コードをテストする場合は、 ScalaTest のようなjUnitよりも scalish なものを使用することをお勧めします。

import java.io.IOException

import org.scalatest._
import org.scalatest.FlatSpec
import org.scalatest.matchers.ShouldMatchers

object SomeCode
{
    def apply() = {
        throw new IOException
    }
}

class SomeTest
  extends FlatSpec
  with ShouldMatchers
{
    "Something" should "throw an IOException, TODO: why ?" in
    {
        intercept[IOException] {
            SomeCode()
        }
    }

    it should "also throw an IOException here" in
    {
        evaluating { SomeCode() } should produce [IOException]
    }
}

nocolor.run( new SomeTest )
于 2012-08-08T05:01:15.610 に答える