Parameterized device tests in Scala (with JUnit4)

Is there a way to implement a parameterized unit test using Scala? I am currently using JUnit4 in the rest of my programs, and I would like to continue to use only the "standard" APIs.

I found an example of Junit4 with Groovy , but I have problems with static options. Maybe because I'm also brand new with Scala :-)

I don’t know how

 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 () = {
     }

+7
scala unit-testing junit junit4
source share
2 answers

This is pretty unpleasant, but it works. Two important things that I discovered: a companion object should pass after the test class, a function that returns parameters should return a collection of AnyRef (or Object) arrays. Any arrays will not work. This is the reason I use java.lang.Integer instead of Scala 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 
+9
source share

Most likely you are better off with ScalaTest or Specs. The latter definitely supports parameterized tests and is widely used in the Scala community. The JUnit syntax for parameterized tests is pretty ugly, and its dependency on static declarations will not make the task easier in Scala (maybe you need a companion object).

+2
source share

All Articles