JUnit how set up test class?

Dmitry Sokolov :

I use constructor of test class for mocking objects. But I want to set parameters for stubs mocking objects from each test methods. I tried using constructors parameters of test class, but JUnit limiting this:

java.lang.Exception: Test class should have exactly one public zero-argument constructor

What I should use for this purpose?

Now I use different class for store mocks and it not looks nicely

package testci

import org.junit.Test
import org.mockito.Mockito.*

interface Object {
    fun get(p: Int): Int
}

class setUpMock(val param: Int, val param2: Int) {
    val mock = mock(Object::class.java)!!
    init {
        `when`(mock.get(param)).thenReturn(param2)
    }
}

class HelloTest {
    @Test
    fun `first test`() {
        val sMock = setUpMock(1,2)
        println(sMock.mock.get(1))
    }

    @Test
    fun `second test`() {
        val sMock = setUpMock(1,3)
        println(sMock.mock.get(1))
        verify(sMock.mock).get(1)
    }
}
davidxxx :

The default JUnit 4 runner doesn't provide such a feature : parameterized tests.
To use it, you need to annotate your class with the Parameterized runner class and to define a @Parameterized.Parameters function that sets the parameter values for each scenario.

For example :

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

@RunWith(Parameterized::class)
class HelloTest(val param1: Int, val param2: Int) {

    companion object {
        @JvmStatic
        @Parameterized.Parameters
        fun data() = listOf(
                arrayOf(1, 2),
                arrayOf(1, 3)
        )
    }
    @Test
    fun `first test`() {
        val sMock = setUpMock(param1, param2)
        println(sMock.mock.get(1))
    }

    @Test
    fun `second test`() {
        val sMock = setUpMock(param1, param2)
        println(sMock.mock.get(1))
        verify(sMock.mock).get(1)
    }
}

No tested code but you should get the idea.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=130344&siteId=1