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?
There are other NUnit attributes that enable you to write a suite of similar tests. A [TestCase] attribute is used to create a suite of tests that execute the same code but have different input arguments. You can use the [TestCase] attribute to specify values for those inputs.
JUnit Classes Assert − Contains a set of assert methods. TestCase − Contains a test case that defines the fixture to run multiple tests. TestResult − Contains methods to collect the results of executing a test case.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With