如何在Scala中使用JUnit ExpectedException?

Jay*_*ker 6 junit scala exception

我希望能够在Scala中使用JUnit 4.7的ExpectedException @Rule.但是,似乎没有任何东西:

import org.junit._

class ExceptionsHappen {

  @Rule 
  def thrown = rules.ExpectedException.none

  @Test
  def badInt: Unit = {
    thrown.expect(classOf[NumberFormatException])
    Integer.parseInt("one")
  }
}
Run Code Online (Sandbox Code Playgroud)

这仍然失败了NumberFormatException.

Mat*_*ell 8

编辑:在JUnit 4.11发布之后,您现在可以使用注释方法@Rule.

您将使用它:

private TemporaryFolder folder = new TemporaryFolder();

@Rule
public TemporaryFolder getFolder() {
    return folder;
}
Run Code Online (Sandbox Code Playgroud)

对于早期版本的JUnit,请参阅下面的答案.

-

不,你不能直接从Scala使用它.该领域需要是公开的和非静态的.来自 org.junit.Rule:

public @interface Rule: Annotates fields that contain rules. Such a field must be public, not static, and a subtype of TestRule.

您无法在Scala中声明公共字段.所有字段都是私有的,并且可以通过访问者访问.看到这个问题的答案.

除此之外,还有针对junit的增强请求(仍然是Open):

扩展规则以支持@Rule public MethodRule someRule(){return new SomeRule(); }

另一种选择是允许非公共字段,但这已被拒绝:在非公共字段上允许@Rule注释.

所以你的选择是:

  1. 克隆junit,并实现第一个建议,方法,并提交拉取请求
  2. 从实现@Rule的java类扩展Scala类

-

public class ExpectedExceptionTest {
    @Rule
    public ExpectedException thrown = ExpectedException.none();
}
Run Code Online (Sandbox Code Playgroud)

然后继承自:

class ExceptionsHappen extends ExpectedExceptionTest {

  @Test
  def badInt: Unit = {
    thrown.expect(classOf[NumberFormatException])
    Integer.parseInt("one")
  }
}
Run Code Online (Sandbox Code Playgroud)

哪个工作正常.

  • 为清楚起见:它(现在)适用于 scala(但仅适用于方法:`@Rule def myRule = ...`,而不适用于诸如 `@Rule val myRule = ...` 之类的属性) (2认同)

lmm*_*lmm 8

为了在Scala中使用JUnit 4.11 ,您应该对注释进行元注释,以便注释仅应用于(合成)getter方法,而不是基础字段:

import org.junit._
import scala.annotation.meta.getter

class ExceptionsHappen {

  @(Rule @getter)
  def thrown = rules.ExpectedException.none

  @Test
  def badInt: Unit = {
    thrown.expect(classOf[NumberFormatException])
    Integer.parseInt("one")
  }
}
Run Code Online (Sandbox Code Playgroud)