Restart Function That Is Running
I have a function that calls a test on each object. I want to be able to retest if the current test fails.
foreach (TestObject test in Tests)
{
test.RunTest()
}
//This is in the TestObject class
RunTest()
{
if (failure)
{
//W开发者_JS百科ant to be able to run RunTest() again without interrupting the foreach loop.
}
}
You guys like too much code...
for (var tryCount = 0; tryCount < 3; tryCount++)
if (test.RunTest())
break;
... oh I thought of an even shorter version... but it's not as clean ...
for (var tryCount = 0; !test.RunTest() && tryCount < 3; tryCount++);
If you want reuse then something like this...
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);
For both answers above, the solutions will result in RunTest() running forever if the failure is legitimate (i.e. not a transient failure, which I can only guess is what you're hitting). You may consider doing one of the loops above, but instead keep a count of how many failures and bail out once that threshold is reached. Something like:
int FailureThreshold = 3;
foreach (TestObject test in Tests)
{
int failCount = 0;
while (failCount < FailureThreshold)
{
if (test.RunTest())
{
break;
}
else
{
failCount++;
}
}
}
You should also consider keeping statistics for how many times you need to loop in order to pass. This could be a great indicator of test stability.
There are several ways you could go about doing this, depending on why exactly you want to do this. You could:
1) Have RunTest()
return boolean
for success or failure, and then:
foreach (TestObject test in Tests)
{
while(!test.runTest(){}
}
2) Use a while
inside of RunTest()
:
RunTest()
{
while(true)
{
...test stuff...
if(failure)
continue;
else
break;
}
}
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
}
精彩评论