views:

55

answers:

1

As I understand, with JUnit 4.x and its annotation org.junit.runners.Parameterized I can make my unit test "parameterized", meaning that for every set of params provided the entire unit test will be executed again, from scratch.

This approach limits me, since I can't create a "parameterized method", for example:

..
@Test 
public void testValid(Integer salary) {
  Employee e = new Employee();      
  e.setSalary(salary);
  assertEqual(salary, e.getSalary());
}
@Test(expected=EmployeeInvalidSalaryException.class) 
public void testInvalid(Integer salary) {
  Employee e = new Employee();      
  e.setSalary(salary);
}
..

As seen in the example, I need two collections of parameters in one unit test. Is it possible to do in JUnit 4.x? It is possible in PHPUnit, for example.

ps. Maybe it's possible to realize such mechanism in some other unit-testing framework, not in JUnit?

+2  A: 

Simple workaround (that I assume is out of scope for this question) is to break them into 2 separate parameterized tests.

If you are inclined on keeping them together then adding extra element to parameterized set of parameters does the trick for you. This element should indicate if given parameter is for one test or another (or for both if needed).

private Integer salary;
private boolean valid;

@Test 
public void testValid() {
  if (valid) {
    Employee e = new Employee();      
    e.setSalary(salary);
    assertEqual(salary, e.getSalary());
  }
}

@Test(expected=EmployeeInvalidSalaryException.class) 
public void testInvalid() {
  if (!valid) {
    Employee e = new Employee();      
    e.setSalary(salary);
  }else {
    throw new EmployeeInvalidSalaryException();
  }
}

JUnit parameterized tests serve classes - not methods, so breaking it up works much better.

grigory