java - 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()
解决方案
如果我们想用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
推荐阅读
- kotlin - 检查列表中的枚举组合 (Kotlin)
- visual-studio-code - 为什么 Prettier 在 React 代码中添加了这些奇怪的字符串
- sql - Oracle 中不区分大小写的 where-in SQL 查询
- html - Nuxtjs/Vuejs 为 datetime-local 类型的输入字段设置默认日期时间为当前日期时间
- python - 如何在没有出现在 URL 中的 CBV 中获取 Django PK 值?
- linux - 如何重新生成spec2006?
- python - 在 Excel 中打开 OData 服务时出错,EDMX 元数据不正确
- python - 如何设置 rpy2 以使用 CX_Freeze 将其构建为 .exe 文件?
- python - 无法建立连接,因为目标机器主动拒绝它 Python
- node.js - 在 MERN 堆栈中使用屏幕截图进行时间跟踪(Reactjs、Nodejs、Expressjs 和 MongoDB)