重启正在运行的功能

时间:2010-06-18 20:05:11

标签: c# c#-4.0

我有一个函数可以调用每个对象的测试。如果当前测试失败,我希望能够重新测试。

        foreach (TestObject test in Tests)
        {
              test.RunTest()
        }
        //This is in the TestObject class
        RunTest()
        {
             if (failure)
             {
                 //Want to be able to run RunTest() again without interrupting the foreach loop.
             }
        }

4 个答案:

答案 0 :(得分:5)

你们这些代码太多了......

for (var tryCount = 0; tryCount < 3; tryCount++)
    if (test.RunTest())
        break;

...哦,我想到了一个更短的版本...但它不是那么干净......

for (var tryCount = 0; !test.RunTest() && tryCount < 3; tryCount++);

如果你想重复使用,那就像这样...

static bool RunTest(Func<bool> testCase, int maxRetry)
{
    for (var tryCount = 0; tryCount < maxRetry; tryCount++)
        if (testCase())
            return true;
    return false;
}

// usage
var testResult = RunTest(test.RunTest, 3);

// or even...
var testResult = RunTest(
    {
        try {
            return test.RunTest();
        } catch (Exception ex) {
            Debug.WriteLine(ex);
            return false;
        }
    }, 3);

答案 1 :(得分:2)

对于上面的两个答案,解决方案将导致RunTest()永远运行,如果失败是合法的(即不是瞬态故障,我只能猜测你正在打什么)。您可以考虑执行上述其中一个循环,而是计算一旦达到该阈值就会失败多少次并挽救。类似的东西:

int FailureThreshold = 3;
foreach (TestObject test in Tests) 
{
    int failCount = 0;

    while (failCount < FailureThreshold)
    {
        if (test.RunTest())
        {
            break;
        }
        else
        {
            failCount++;
        }
    }
}

您还应该考虑保留循环以便传递多少次的统计信息。这可能是测试稳定性的一个很好的指标。

答案 2 :(得分:0)

有几种方法可以实现这一目标,具体取决于您为什么要这样做。你可以:

1)让RunTest()返回boolean表示成功或失败,然后:

foreach (TestObject test in Tests)
{
    while(!test.runTest(){}
}

2)使用while内的RunTest()

RunTest()
{
  while(true)
  {
    ...test stuff...

    if(failure)
      continue;
    else
      break;
  }
}

答案 3 :(得分:0)

foreach (TestObject test in Tests)
{
      test.RunTest()
}
//This is in the TestObject class
RunTest()
{
     //set it to failure or set variable to failure
     while (failure)
     {
         //do the test
         //if using variable set it to failure if it failed, success if it succeeded 
         //will keeping going through the while statement until it succeeds or you cut it off another way
     }
     // has succeeded
}
相关问题