本文介绍了如何在Scala中使用JUnit ExpectedException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够使用JUnit 4.7的 ExpectedException @ Scala中的规则.但是,它似乎并没有捕获到任何东西:

I'd like to be able to use JUnit 4.7's ExpectedException @Rule in Scala. However, it doesn't seem to catch anything:

import org.junit._

class ExceptionsHappen {

  @Rule 
  def thrown = rules.ExpectedException.none

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

这仍然失败,并显示NumberFormatException.

推荐答案

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

Following the release of JUnit 4.11, you can now annotate a method with @Rule.

您将以如下方式使用它:

You will use it like:

private TemporaryFolder folder = new TemporaryFolder();

@Rule
public TemporaryFolder getFolder() {
    return folder;
}

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

For earlier versions of JUnit, see the answer below.

-

否,您不能直接从Scala使用此功能.该字段必须是公共的且非静态的.从 org.junit.Rule :

No, you can't use this directly from Scala. The field needs to be public and non-static. From 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中声明公共字段.所有字段均为私有字段,可供访问者访问.请参阅此问题的答案.

You cannot declare a public fields in Scala. All fields are private, and made accessible by accessors. See the answer to this question.

与此同时,已经有一个对junit的增强请求(仍处于打开"状态):

As well as this, there is already an enhancement request for junit (still Open):

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

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

The other option is that it non-public fields be allowed, but this has already been rejected: Allow @Rule annotation on non-public fields.

因此,您的选择是:

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

-

public class ExpectedExceptionTest {
    @Rule
    public ExpectedException thrown = ExpectedException.none();
}

,然后从中继承:

class ExceptionsHappen extends ExpectedExceptionTest {

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

可以正常工作.

这篇关于如何在Scala中使用JUnit ExpectedException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 12:43