JUnit equivalent to NUnit’s testcase attribute

junitnunittestcasetestcaseattributeunit testing

I've googled for JUnit test case, and it comes up with something that looks a lot more complicated to implement – where you have to create a new class that extends test case which you then call:

public class MathTest extends TestCase {
    protected double fValue1;
    protected double fValue2;

    protected void setUp() {
       fValue1= 2.0;
       fValue2= 3.0;
    }
 }

public void testAdd() {
   double result= fValue1 + fValue2;
   assertTrue(result == 5.0);
}

but what I want is something really simple, like the NUnit test cases

[TestCase(1,2)]
[TestCase(3,4)]
public void testAdd(int fValue1, int fValue2)
{
    double result= fValue1 + fValue2;
    assertIsTrue(result == 5.0);
}

Is there any way to do this in JUnit?

Best Answer

2017 update: JUnit 5 will include parameterized tests through the junit-jupiter-params extension. Some examples from the documentation:

Single parameter of primitive types (@ValueSource):

@ParameterizedTest
@ValueSource(strings = { "Hello", "World" })
void testWithStringParameter(String argument) {
    assertNotNull(argument);
}

Comma-separated values (@CsvSource) allows specifying multiple parameters similar to JUnitParams below:

@ParameterizedTest
@CsvSource({ "foo, 1", "bar, 2", "'baz, qux', 3" })
void testWithCsvSource(String first, int second) {
    assertNotNull(first);
    assertNotEquals(0, second);
}

Other source annotations include @EnumSource, @MethodSource, @ArgumentsSource and @CsvFileSource, see the documentation for details.


Original answer:

JUnitParams (https://github.com/Pragmatists/JUnitParams) seems like a decent alternative. It allows you to specify test parameters as strings, like this:

@RunWith(JUnitParamsRunner.class)
public class MyTestSuite {
    @Test
    @Parameters({"1,2", "3,4"})
    public testAdd(int fValue1, int fValue2) {
       ...
    }
}

You can also specify parameters through separate methods, classes or files, consult the JUnitParamsRunner api docs for details.