简体   繁体   English

如何使用 Ava 创建参数测试

[英]How to create parametric tests with Ava

Coming from Python, I am used to this syntax when writing parametric tests (hope it is self-explanatory):来自 Python,我在编写参数测试时习惯了这种语法(希望它是不言自明的):

@pytest.mark.parametrize('a', [0, 1, 2])
@pytest.mark.parametrize('b', [0, 1, 2])
def test_sum(a, b):
    assert sum(a, b) == a + b

The testing framework will then run test_sum() for each combination of a and b , considering each combination as a different test (ie: the 9 combinations can fail/pass independently).然后,测试框架将为ab每个组合运行test_sum() ,将每个组合视为不同的测试(即:9 个组合可以独立失败/通过)。

I have been playing around with Ava and, using macros, I can easily run the same test with different parameters:我一直在玩Ava并且使用宏,我可以轻松地使用不同的参数运行相同的测试:

import test from "ava";

function sum(a, b) {
    return a + b;
}

function macroSum(t, a, b) {
    t.is(sum(a, b), a + b);
}
macroSum.title = (providedTitle = "", a, b) =>
    `${providedTitle}: ${a} + ${b}`

test(macroSum, 0, 0);
test(macroSum, 0, 1);
test(macroSum, 0, 2);
test(macroSum, 1, 0);
test(macroSum, 1, 1);
test(macroSum, 1, 2);
test(macroSum, 2, 0);
test(macroSum, 2, 1);
test(macroSum, 2, 2);

The only problem is that I need to call test() multiple times explicitly.唯一的问题是我需要多次明确地调用test() Is there any way I could do what I am used to do in Python?有什么办法可以做我习惯在 Python 中做的事情吗? (declare a list of values for each parameter and let the framework combine them and run all the combinations for me) (为每个参数声明一个值列表,让框架组合它们并为我运行所有组合)

Note it is not the same as embedding a loop inside a test.请注意,这与在测试中嵌入循环不同。 With parametric tests each combination is a separate test to the framework, with a different title/identifier and which can fail/pass independently of the other parameter combinations.对于参数测试,每个组合都是对框架的单独测试,具有不同的标题/标识符,并且可以独立于其他参数组合失败/通过。

That means, what I am looking for is not a single test like:这意味着,我正在寻找的不是一个单一的测试,如:

test('all combinations', t => {
  [0, 1, 2].forEach(a => {
    [0, 1, 2].forEach(b => {
      t.is(sum(a, b), a + b);
    });
  });
});

No. Your best bet is to loop over an array of parameters:不。最好的办法是循环遍历一组参数:

for (const params of [
  [1, 0],
  [1, 1],
]) {
  test(macroSum, ...params)
}

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

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