代码之家  ›  专栏  ›  技术社区  ›  IAdapter

JUnit@Rule将参数传递给测试

  •  12
  • IAdapter  · 技术社区  · 15 年前

    我想创造 @Rule 能做这样的事

    @Test public void testValidationDefault(int i) throws Throwable {..}
    

    其中i是传递给测试的参数 .

    不管我怎么想

    java.lang.Exception: Method testValidationDefault should have no parameters
    

    ?

    5 回复  |  直到 13 年前
        1
  •  11
  •   pinkpanther    6 年前

    实现一个保存所有参数值的规则,对每个参数值计算一次测试,并通过一个方法提供值,这样测试就可以从规则中提取这些值。

    考虑这样一个规则(伪代码):

    public class ParameterRule implements MethodRule{
        private int parameterIndex = 0;
        private List<String> parameters;
        public ParameterRule(List<String> someParameters){ 
            parameters = someParameters;
        }
    
        public String getParameter(){
            return parameters.get(parameterIndex);
        }
    
        public Statement apply(Statement st, ...){
            return new Statement{
                 public void evaluate(){
                     for (int i = 0; i < parameters.size(); i++){
                         int parameterIndex = i;
                         st.evaluate()
                     }      
                 }
            }
        }
    }
    

    您应该能够在这样的测试中使用它:

     public classs SomeTest{
         @Rule ParameterRule rule = new ParameterRule(ArrayList<String>("a","b","c"));
    
         public void someTest(){
             String s = rule.getParameter()
    
             // do some test based on s
         }
     }
    
        2
  •  8
  •   MarcoS    11 年前

    @Parameters @RunWith(value = Parameterized.class) 用于将值传递给测试。可以找到一个例子 here .

    我不知道那件事 @Rule 但是在阅读之后 this post

    如果在测试类中,您创建了一个指向实现MethodRule接口的对象的字段,并通过添加@rule实现将其标记为作为规则处理,那么JUnit将为它将运行的每个测试回调实例,从而允许您围绕测试执行添加其他行为。

    我希望这有帮助。

        3
  •  1
  •   piotrek    13 年前

    zohhak 项目。它允许您使用参数编写测试(但它是一个运行程序,而不是一个规则):

    @TestWith({
       "25 USD, 7",
       "38 GBP, 2",
       "null,   0"
    })
    public void testMethod(Money money, int anotherParameter) {
       ...
    }
    
        4
  •  0
  •   David H. Clements    14 年前

    Theories @DataPoints / @DataPoint .

    例如:

    @RunWith(Theories.class)
    public class TestDataPoints {
    
        @DataPoints
        public static int [] data() {
            return new int [] {2, 3, 5, 7};
        }
    
        public int add(int a, int b) {
            return a + b;
        }
    
        @Theory
        public void testTheory(int a, int b) {
            System.out.println(String.format("a=%d, b=%d", a, b));
            assertEquals(a+b, add(a, b));
        }
    }
    

    输出:

    a=2, b=2
    a=2, b=3
    a=2, b=5
    a=2, b=7
    a=3, b=2
    a=3, b=3
    a=3, b=5
    a=3, b=7
    a=5, b=2
    a=5, b=3
    a=5, b=5
    a=5, b=7
    a=7, b=2
    a=7, b=3
    a=7, b=5
    a=7, b=7
    

        5
  •  -4
  •   IAdapter    15 年前

    这是做不到的,即使使用@Rule,也不能将参数传递给测试方法。