简体   繁体   English

是否有可能使测试方法参数化,而不是整个类?

[英]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. 据我所知,使用JUnit 4.x及其注释org.junit.runners.Parameterized我可以使我的单元测试“参数化”,这意味着对于每组参数,只要从头开始再次执行整个单元测试。

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? 是否可以在JUnit 4.x中执行? It is possible in PHPUnit, for example. 例如,它可以在PHPUnit中使用。

ps. PS。 Maybe it's possible to realize such mechanism in some other unit-testing framework, not in JUnit? 也许有可能在其他一些单元测试框架中实现这种机制,而不是在JUnit中?

yes, it's possible. 是的,这是可能的。 recently i started zohhak project. 最近我开始了zohhak项目。 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. JUnit参数化测试服务于类 - 而不是方法,因此分解它会更好。

另一种选择是使用JCheckQuickCheck for Java

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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