在ScalaTest中使用JUnit @Rule(例如TemporaryFolder) [英] Using JUnit @Rule with ScalaTest (e.g. TemporaryFolder)

查看:100
本文介绍了在ScalaTest中使用JUnit @Rule(例如TemporaryFolder)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够使用JUnit规则,例如TemporaryFolder或我们已经内部开发的其他TestRule. 最好的方法是什么?我知道JUnitSuite,但它似乎没有使用@Rule批注. 我仍然想使用其他ScalaTest套件.

I would like to be able to use JUnit rules such as TemporaryFolder or other TestRules we have already developed in-house. What is the best method to accomplish that? I'm aware of JUnitSuite but it doesn't seem to pick up the @Rule annotation. I would like to use a different ScalaTest suite anyway.

所以我的问题是:

  • ScalaTest诉讼是否支持JUnit规则?
  • 如果没有,是否存在可以使用Junit TestRule的图书馆?
  • 如果没有,如何在Scala测试中使用JUnit TestRule?
  • 或者还有一种更合适的Scala特定方法来完成TemporaryFolder的内容,或者例如Stefan Birkner的系统规则提供?
  • Are JUnit rules supported by a ScalaTest suit?
  • If not, is there a library out there which would make using Junit TestRules possible?
  • If not, how to use JUnit TestRules in Scala tests?
  • Or is there a more appropriate Scala-specific approach for acomplishing what TemporaryFolder, or, e.g., Stefan Birkner's System Rules provide?

这是我尝试使用JUnitSuite的方法:

Here's what I tried with JUnitSuite:

class MyTest extends JUnitSuite {
  //@Rule
  //val temporaryFolder = new TemporaryFolder() // throws java.lang.Exception: The @Rule 'temporaryFolder' must be public.

  @Rule
  def temporaryFolder = new TemporaryFolder()

  @Test
  def test: Unit = {
    assert(temporaryFolder.newFile() !== null) // java.lang.IllegalStateException: the temporary folder has not yet been created
  }
}

推荐答案

您可以通过创建类型为TemporaryFolder的成员字段并通过@Rule函数返回该字段值来解决该问题.

You could solve the problem by creating a member field of type TemporaryFolder and returning this field value by the @Rule function.

class MyTest extends JUnitSuite {

  val _temporaryFolder = new TemporaryFolder

  @Rule
  def temporaryFolder = _temporaryFolder

  @Test
  def test: Unit = {
    assert(temporaryFolder.newFile() !== null)
  }
}

这篇关于在ScalaTest中使用JUnit @Rule(例如TemporaryFolder)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆