本文介绍了初始化并清理TestNG中并行测试的每个测试数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在将一些测试从JUnit迁移到TestNG时,我遇到了一个问题,因为这些测试框架如何处理它们的Test类实例。

While migrating some tests from JUnit to TestNG, I'm facing an issue because of the difference in how these test frameworks treat their Test class instances.

JUnit创建每个测试方法的Test类的新实例。所以我看到的一个常见模式是:

JUnit creates a new instance of the Test class for each test method. So a common pattern I see is:

public class MyTest {

    private Stream inputData;

    @Before
    public void setUp() {
        // Set up some data in (non-static) instance fields
        // This data is isolated per test
        inputData = createInputDataStream();
    }

    @Test
    public void testStuff() {
        // Use the data from the instance fields
        doStuff(inputData);
    }

    @After
    public void tearDown() {
        // Clean up the data from the instance fields
        closeInputDataStream(inputData);
    }
}

相比之下,TestNG使用单个测试实例所有测试方法的类。所以上面的模式不起作用!由于数据存储在实例字段中,因此不再隔离这些值。如果启用并行执行,这可能会导致覆盖数据中期测试。

In contrast, TestNG uses a single instance of the Test class for all test methods. So the pattern above does not work! Because data is stored in instance fields, the values are no longer isolated. This can cause overwritten data mid-test if parallel execution is enabled.

那么我如何使用TestNG执行此操作?有没有办法存储隔离到每个 @BeforeMethod - @Test - 的数据@AfterMethod 元组?

So how would I do this with TestNG? Is there a way to store data which is isolated to each @BeforeMethod-@Test-@AfterMethod tuple?

我可以在 @Test 本身内完成所有3个步骤,但这需要添加笨拙的尝试...最后阻止每个测试。我也尝试使用 ITestContext ,但它似乎也在整个测试运行中共享。

I can do all 3 steps inside the @Test itself, but that would require adding ungainly try...finally blocks to every test. I also tried using ITestContext, but it also seems to be shared for the entire test run.

推荐答案

是的,使用TestNG,您对使用JUnit所做的局部变量有更多的权力,并且DataProvider处理您的线程,每个测试类实例:

Yes, with TestNG you have way more power over those local variables that you did with JUnit AND the DataProvider handles your threading, per test-class-instance:

public class MyTest {

private Stream inputData;

@BeforeMethod
public void setUp(Object[] args) {
    inputData = (Data)args[0]; 
    inputData = normalizeDataBeforeTest(inputData);
}

@Test(dataProvider="testArgs")
public void testStuff(Data inputDatax, Object a, Object b) {
    doSomethingWith(a);
    doSomethingWith(b);
    doStuff(this.inputData);
}

@AfterMethod
public void tearDown() {
    // Clean up the data from the instance fields
    closeInputDataStream(inputData);
}

....
@DataProvider
public static Object[][] testArgs() {
    // generate data here, 1 row per test thread
  Object[][] testData;
  for loop {
      // add row of data to testData
      // {{dataItem, obja, objb}, {dataItem, obja, objb}} etc.
  }
  return testData;
}
}

这篇关于初始化并清理TestNG中并行测试的每个测试数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 10:00