首页 > 解决方案 > JUnit 5:如何断言在 Scala 中引发了异常?

问题描述

版本:

jdk1.8.0 斯卡拉:2.11

<properties>
 <junit.jupiter.version>5.2.0</junit.jupiter.version>
  <junit.platform.version>1.2.0</junit.platform.version>
</properties>
<dependency>
  <groupId>org.mockito</groupId>
  <artifactId>mockito-all</artifactId>
  <version>1.9.5</version>
  <scope>test</scope>
</dependency>
<dependency>
  <groupId>org.junit.jupiter</groupId>
  <artifactId>junit-jupiter-api</artifactId>
  <version>${junit.jupiter.version}</version>
  <scope>test</scope>
</dependency>
<dependency>
  <groupId>org.junit.jupiter</groupId>
  <artifactId>junit-jupiter-engine</artifactId>
  <version>${junit.jupiter.version}</version>
  <scope>test</scope>
</dependency>

我正在关注这个问题,它展示了如何在 java 中使用 junit 5 断言异常。

当我试图在 scala 中做同样的事情时:

val closureContainingCodeToTest = () -> myClass.myMethod(data)   // or     val closureContainingCodeToTest = () => myClass.myMethod(data)
assertThrows(classOf[MyException], closureContainingCodeToTest)

我收到此错误:

 Error:(89, 48) type mismatch;
 found   : () => Unit
 required: org.junit.jupiter.api.function.Executable
    assertThrows(classOf[MyException], closureContainingCodeToTest)

这可能是一个非常简单的问题,但我找不到如何在 Scala 中为 JavaExecutable对象创建 Scala 闭包。

编辑:

添加一个简单的完整测试:

package com.my.lib

import org.junit.jupiter.api.Assertions.assertThrows
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.function.Executable

class myTest {

  @Test
  def myTest = {
    val closureContainingCodeToTest:Executable = () => throw new RuntimeException()
    assertThrows(classOf[RuntimeException], closureContainingCodeToTest)
  }
}

我收到以下错误:

Error:(11, 53) type mismatch;
 found   : () => Nothing
 required: org.junit.jupiter.api.function.Executable
    val closureContainingCodeToTest:Executable = () => throw new RuntimeException()

标签: javascalaunit-testingjunitjunit5

解决方案


如果我们想用Junit 5风格来​​做 - 你可以在下面的代码中做:

import org.junit.jupiter.api.{DisplayName, Test}
import org.junit.runner.RunWith
import org.scalatest.junit.{JUnitRunner, JUnitSuite}

@RunWith(classOf[JUnitRunner])
class Junit_5_Test extends JUnitSuite{

  object ExceptionTest {
    @throws(classOf[RuntimeException])
    def throwRunEx = throw new RuntimeException
  }

  @Test
  @DisplayName("Example with JUnitSuite")
  def throwsExceptionWhenCalled_With_JUnitSuite() {
    import ExceptionTest._
    assertThrows[RuntimeException]{ throwRunEx}
  }

}

要这样做 - 您需要将其包含在您的build.sbt

"org.junit.jupiter" % "junit-jupiter-api" % "5.2.0" % Test,
 "org.scalatest" %% "scalatest" % "3.2.0-SNAP10" % Test

推荐阅读