There is a nice possibility to run JUnit test with parameters where the same test method is executed multiple times with different data as described here: http://junit.org/apidocs/org/junit/runners/Parameterized.html
Unfortunately, it only seems possible to use primitive parameters or Strings, but not objects. Is there any workaround known for this?
The type of the data()
method in the use of the @Parameters annotation is List<Object[]>
, so you can put in any object.
To pass in, e.g., a Money
object, your array to be converted to a list would be:
{ { new Money(26, "CHF") },
{ new Money(12, "USD") } }
The constructor of the test class should take a Money object as argument then.
recently i started zohhak project. it lets you write:
@TestWith({
"25 USD, 7",
"38 GBP, 2",
"null, 0"
})
public void testMethod(Money money, int anotherParameter) {
...
}
Use JUnitParams instead... junitparams.googlecode.com
Using object is also possible using Junit @Parameters
.
Example:-
@RunWith(Parameterized.class)
public class TestParameter {
@Parameter(value=0)
public int expected;
@Parameter(value=1)
public int first;
@Parameter(value=2)
public int second;
private Calculator myCalculator;
@Parameters(name = "Test : {index} : add({1}+{2})= Expecting {0}")//name will be shared among all tests
public static Collection addNumbers() {
return Arrays.asList(new Integer[][] { { 3, 2, 1 }, { 5, 2, 3 }, { 9, 8, 1 }, { 200, 50, 150 } });
}
@Test
public void testAddWithParameters() {
myCalculator = new Calculator();
System.out.println(first + " & " + second + " Expected = " + expected);
assertEquals(expected, myCalculator.Add(first, second));
}
}