I want to log the unit test names in Scala automatically. The solution with org.junit.rules.TestName
works fine in Java, but not in Scala.
Consider the following code snippet:
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)
}
}
It compiles fine, but when running I receive the following error message:
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
The Java counterpart works as expected.
I've already tried the following (according to Using JUnit @Rule with ScalaTest (e.g. TemporaryFolder)):
val _testName = new TestName
@Rule def testName = _testName
but this did not really help. In this version the test cases run, but the {testName} results always {null}.
The default access rule in Scala is public, and therefore there is no public
keyword. On the other hand, the JUnit framework seems to consider it non-public.
Does anyone know how to overcome this problem? Another similar solution would also be fine! Thank you!