在TestNG中的线程之间共享数据

时间:2012-12-24 06:41:33

标签: testng

我在testmethod testNG threadPoolSize = 10 @Test(threadPoolSize = 10, invocationCount = 10) public void testCreate(){ long StartTime = new Date().getTime() ; //operation to create records long EndTime = new Date().getTime() ; } ,在数据库中创建记录

我需要计算所有线程创建所有记录所花费的总时间 请帮我找到相同的。

{{1}}

如何计算上述代码中所有线程所用的时间?

上面的代码给了我一次只有一个线程的时间。

2 个答案:

答案 0 :(得分:0)

我会调用一个类似startTick()的外部函数,它会跟踪startTime,然后一旦设置,就不会被覆盖,并且会收集所有结束时间的endTick()。在afterTest中,我可以做endTick - startTick ......类似于:

startTick(){
  if(startTime == null)
    startTime = new Date().getTime();
}

testCreate() {
  startTick(); 
        //operation to create records
  endTick();
}

endTick(){
    endTime = new Date().getTime();
}
@AfterTest
afterTest(){
  endTime - startTime;
}

答案 1 :(得分:0)

听起来您需要发布有关测试时间的数据,以便它可以在报告中使用,而不是在同一测试的其他线程中使用。

为此,您可以将每个测试的结果存储在某个中心位置,稍后查找总计。以下是否适合您?

public class TimeTest {
    Map<Long, Long> timeRecord = new ConcurrentHashMap<Long, Long>();

    @Test(threadPoolSize = 10, invocationCount = 10)
    public void testCreate(){
        long threadID = Thread.currentThread().getId();
        long startTime = new Date().getTime() ; 

        //operation to create records

        long endTime = new Date().getTime();
        long diffTime = endTime - startTime;
        timeRecord.put(threadID, diffTime);
        // Log time taken
        System.out.println("TestMethod[" + threadID + "] TestTime: " + diffTime);
    }

    @AfterTest
    public void displayTime() {
        long runtime = 0;
        for (Long threadID : timeRecord.keySet()) {
            runtime += timeRecord.get(threadID);
        }
        System.out.println("AfterSuite TotalTime: " + runtime);
    }

}

如果您想要对整个测试进行计时,而不仅仅是测试的一部分,您可以使用TestNG提供的ITestResult接口。

@AfterMethod
public void recordTime(ITestResult testResult){
    long threadID = Thread.currentThread().getId();
    long timeDiff = testResult.getEndMillis() - testResult.getStartMillis();
    // Log time taken
    System.out.println("AfterMethod[" + threadID + "] TestTime: " + timeDiff);
}

但是,时间可能与上面的时间不同,因为可能会有额外的开销。