简体   繁体   中英

is it possible to make test method parameterized, not an entire class?

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?

yes, it's possible. 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) {
   ...
}

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.

另一种选择是使用JCheckQuickCheck for Java

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM