Search code examples
unit-testingscalajunitjunit4

Parameterized Unit Tests in Scala (with JUnit4)


Is there a way to implement a parameterized unit 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() = {
    }


Solution

  • 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