我想设置一个预期的例外JUnit4测试使用卡拉.我现在做的事情相似的如下:

@Test(expected=classOf[NullPointerException])
def someTest() = {
    // Some test code
}

但我得到以下编译错误:

error: wrong number of arguments for constructor Test: ()org.junit.Test
有帮助吗?

解决方案

一路斯的交易的属性是一个小时髦。我想什么你想要做的应该是表达这样的:

@Test { val expected = classOf[ NullPointerException] }
def someTest {
    // test code
}

其他提示

这是期待了一下,但在2.8注释语法改变是一样的,你最初发布的内容。特里斯坦发布的语法是当前稳定版本是正确的,但是当我升级我的项目每晚2.8编译器它给我的错误。我猜这是由于包含命名和默认参数的。还有上的一些讨论 Scala的邮件列表。引述的Lukas Rytz:

  

另外请注意,在对2.8.0 Java注解的语法将不再使用的名称 - 值   对但命名参数代替,即

@ann{ val x = 1, val y = 2}  ==>  @ann(x = 1, y = 2)

您也可以尝试规格有:

class mySpec extends SpecificationWithJUnit {
  "this expects an exception" in {
     myCode must throwA[NullPointerException]
  }
}

埃里克。

使用ScalaTest和JUnit一起,你可以这样做:

import org.scalatest.junit.JUnitSuite
import org.scalatest.junit.ShouldMatchersForJUnit
import org.junit.Test

class ExampleSuite extends JUnitSuite with ShouldMatchersForJUnit {

  @Test def toTest() {
    evaluating { "yo".charAt(-1) } should produce [StringIndexOutOfBoundsException]
  }
}

这对我的作品(JUnit的4.10,斯卡拉2.10.2):

@Test(expected = classOf[NullPointerException])
def testFoo() {
    foo(null)
}

什么特里斯坦建议类似,但这种语法实际上编译并在我的项目工作。

编辑:嗯,仔细一看,这正是原来的问题有哪些。嗯,我想拥有最新的工作语法也回答不受到伤害。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top