即时重新运行失败的测试

Rerun failed test on the fly

我的一些测试需要外部资源。很少见,但有时会出现资源超时异常,导致测试失败。

我可以知道失败的原因是不是超时,我想在它完全失败之前让测试有第二次机会运行。

那么,有什么方法可以在结束后(在 TestCleanup 中)重新运行 测试吗?

没有。您必须检查相关单元测试中的超时,并在那里实现重试逻辑。

这听起来比实际更复杂。在你的测试方法中,你可以编写自己的重试逻辑,或者使用企业库中的东西来传递调用,即如果在你的测试方法中你有这个:

var result = Instance.PossibleTimeoutMethod();

那么你可以这样做:

[TestMethod, TestCategory("SLOW")]
public void MyTestMethod()
{
    // Arrange (this is not real code, just made for example)
    var retryPolicy = new RetryPolicy{
        attempts = 3,
        timeBetweenAttempts = TimeSpan.FromSeconds(2),
        TimeToWaitBeforeThrowing = TimeSpan.FromSeconds(30)
    }
    ResultType result = null;

    // Act
    retryPolicy.ExecuteAction(() => result = Instance.PossibleTimeoutMethod());

    // Assert
    result.ShouldEqual(expectedResult);
}

Enterprise Library 对你来说可能有些过分,但这里仅供参考: http://www.c-sharpcorner.com/UploadFile/vendettamit/retrypolicy-using-microsoft-practices-enterprise-library/