1

The use case is as follows, I would like to be able to combine parametrized and non parametrized test as well as have different parameters for different parametrized tests.

Using Parameterized.class seems a bit of an overkill as this will blow up the constructor for each new unit test I need to parametrize, also will result in multiple runs of the non parametrized tests which I am not interested in.

So I was thinking about Theories.class , but although multiple @DataPoints can be provided, those refer to individual types passed as each argument to the test function and still results in only one function tested.

I would like to achieve something like

@RunWith(Theories.class)
class Test{
    @Theory(named="foo")
    public void fooTest(Object input) { 
    }

    public static @DataPoints(named="foo") Object[] inputs = {1, 2, 3, 4, 5};

    @Theory(named="bar")
    public void barTest(Object input) { 
    }

    public static @DataPoints(named="bar") Object[] inputs = {6, 7, 8, 9, 10};

    public void bazTest() {
    }
}

Where fooTest is tested with 1, 2, 3, 4, 5 and barTest with 6, 7, 8, 9, 10 respectively.

Is there a way to achieve that using Theorys? Is there any alternative to achieve that?

Community
  • 1
  • 1
Alexandru Barbarosie
  • 2,952
  • 3
  • 24
  • 46

2 Answers2

3

You can't mix test style with the Theories runner. But some third party parameterised runners such as JUnitParams could be used in this way.

e.g

@RunWith(JUnitParamsRunner.class)
public class PersonTest {

  @Test
  @Parameters({"17, false", 
               "22, true" })
  public void personIsAdult(int age, boolean valid) throws Exception {
    assertThat(new Person(age).isAdult(), is(valid));
  }

  @Test
  public void lookNoParams() {
    etc
  }

}
henry
  • 5,923
  • 29
  • 46
  • 1
    I am really looking for an option that uses the out of the box functionality provided by jUnit, alternatives are more for general knowledge improvement. – Alexandru Barbarosie May 05 '16 at 14:33
0

JUnit 5 introduced ParameterizedTest (doc):

@ParameterizedTest
@ValueSource(ints = {2, 4, 6})
public void isEven(Integer val) {
    assertTrue(val % 2 == 0);
}

This is a nice tutorial.

naicolas
  • 138
  • 6