Is there a way to implement a parameterized unit开发者_Go百科 test with Scala? Currently I use JUnit4 in the rest of my programs and I would like to continue using only "standard" APIs.
I found an example for Junit4 with Groovy, but I have problems defining the static
parts. Could be, because I am also quite new with Scala :-)
I am currently as fas as
import org.junit.Test import org.junit.Assert._ import org.junit.runner.RunWith import org.junit.runners.Parameterized import org.junit.runners.Parameterized.Parameters @RunWith(classOf[Parameterized]) class MyTest extends junit.framework.TestCase { @Parameters object data { ... } @Parameter ... @Test def testFunction() = { }
That's quite a nuisance, but it works. Two important things I discovered: companion object must come after test class, the function returning the parameters must return a collection of arrays of AnyRef (or Object). arrays of Any won't work. That the reason I use java.lang.Integer instead of Scala's Int.
import java.{util => ju, lang => jl}
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
import org.junit.runners.Parameterized.Parameters
@RunWith(value = classOf[Parameterized])
class JUnit4ParameterizedTest(number: jl.Integer) {
@Test def pushTest = println("number: " + number)
}
// NOTE: Defined AFTER companion class to prevent:
// Class com.openmip.drm.JUnit4ParameterizedTest has no public
// constructor TestCase(String name) or TestCase()
object JUnit4ParameterizedTest {
// NOTE: Must return collection of Array[AnyRef] (NOT Array[Any]).
@Parameters def parameters: ju.Collection[Array[jl.Integer]] = {
val list = new ju.ArrayList[Array[jl.Integer]]()
(1 to 10).foreach(n => list.add(Array(n)))
list
}
}
The output should be as expected:
Process finished with exit code 0
number: 1
number: 2
number: 3
number: 4
number: 5
number: 6
number: 7
number: 8
number: 9
number: 10
You are probably better off with ScalaTest or Specs. The latter definitely supports parameterized tests, and is widely used in the Scala community. JUnit's syntax for parameterized tests is pretty horrible, and its reliance on static declarations won't make your task easier in Scala (probably you need a companion object).
精彩评论