首页 > 解决方案 > 如何累积 for 循环内的 while 循环的总执行次数?

问题描述

我想累积在 for 循环中的条件 while 循环动作的总尝试次数,以重复测试 while 循环动作的稳定性。(使用 Selenium 框架)

尝试更改循环方法或设置变量,使用我能想到的所有方法并浏览社区,似乎没有人遇到过类似的情况。

public static void main(String[] args) throws Exception {
  for (int loop = 1; loop <= 10; loop++) {
    System.out.println("Loop count: " + loop);
    boolean retry = true;
    int i = 1;
    while (retry == true) {
      int t = i++;
      //...
      System.out.println("Test case 1 - Start Run " + t);
      try {
         // my testing script of actions
        System.out.println("Test case 1 - Run Success, finished by " 
            + t + " execution(s)");
        retry = false;
        break;
      } catch (Exception e) {
        System.out.println("Test case 1 - Run " 
            + t + " Failed, retry...");
      } 
      driver.quit();
    }
  }
}

该代码是通过循环整个事情并查看它实际需要多少次尝试来测试动作脚本(在 Selenium webdriver 框架中)的稳定性,当出现异常错误时(通常它会完全停止脚本),自动重试而无需人为中断完成 10 次成功运行(在每个 for 循环计数结束时打印并累积总 t)。换句话说,我想计算(在重试循环内)达到 10 次成功运行(for 循环)所花费的总尝试次数。

标签: javaseleniumselenium-webdriver

解决方案


为什么不将总数保持在两个循环之外?

int totalCount = 0;

for (int i = 0; i < 10; i ++) {

  while (retry) {
    totalCount ++;
    // do your thing
  }
}

System.out.println("Took " + totalCount + " attempts to get 10 successfully");

推荐阅读