刚开始使用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中的异常处理,发现你应该使用模式匹配器,并且no exception handling in Scala。这究竟是如何工作的?
答案 0 :(得分:4)
如果您正在测试scala代码,我建议使用比ScalaTest等jUnit更精简的东西。
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 )