【发布时间】:2019-01-15 23:23:07
【问题描述】:
我想在 Scala 中自动记录单元测试名称。org.junit.rules.TestName 的解决方案在 Java 中运行良好,但在 Scala 中不行。
考虑以下代码sn-p:
import org.junit._
import org.junit.rules.TestName
class ScalaUnitTestExample {
@Rule val testName = new TestName
@Before def printTestCaseNameBefore() {
print("\nStart of test case " + testName.getMethodName)
}
@After def printTestCaseNameAfter() {
print("\nEnd of test case " + testName.getMethodName)
}
@Test
def checkAddition() {
Assert.assertEquals(5, 2 + 3)
}
@Test
def checkMultiplication() {
Assert.assertEquals(6, 2 * 3)
}
}
编译正常,但运行时收到以下错误消息:
There was 1 failure:
1) initializationError(ScalaUnitTestExample)
java.lang.Exception: The @Rule 'testName' must be public.
at org.junit.internal.runners.rules.RuleFieldValidator.addError(RuleFieldValidator.java:90)
(...)
at scala.tools.nsc.MainGenericRunner.main(MainGenericRunner.scala)
FAILURES!!!
Tests run: 1, Failures: 1
Java 对应项按预期工作。
我已经尝试过以下方法(根据Using JUnit @Rule with ScalaTest (e.g. TemporaryFolder)):
val _testName = new TestName
@Rule def testName = _testName
但这并没有真正帮助。在此版本中,测试用例运行,但 {testName} 结果始终为 {null}。
Scala 中的默认访问规则是公共的,因此没有public 关键字。另一方面,JUnit 框架似乎认为它是非公开的。
有谁知道如何解决这个问题?另一个类似的解决方案也可以!谢谢!
【问题讨论】:
-
为什么不使用 ScalaTest 代替?您将能够在日志中看到测试名称,
@Before和@After有替代名称。 -
第一个选项的问题是
val testName定义了一个字段和一个getter 方法(用Java 术语);默认情况下注释转到字段(但这可以更改:参见scala-lang.org/api/2.11.8/#scala.annotation.meta.package);该字段是私有的(Scala 根本不允许定义非私有字段),但 JUnit 要求它是公共的。令我惊讶的是,第二个选项不起作用。