gpt4 book ai didi

c# - 重试 Visual Studio C# TestMethod

转载 作者:太空狗 更新时间:2023-10-30 00:28:20 25 4
gpt4 key购买 nike

我很想知道在 C# 的 Visual Studio 2008 单元测试框架中是否有任何内置机制可以重试 测试。举个例子,我有一个 C# 单元测试,看起来像这样:

[TestMethod]
public void MyMethod() {
DoSomething();
Assert.Something();
}

现在,偶尔 DoSomething() 表现不佳;在那种情况下,我想在到达断言之前重新运行 DoSomething() 方法。显然我可以做类似的事情:

...
do {
Initialization();
DoSomething();
} while (PerformedOK() == false);
Assert.Something();
...

虽然这有点麻烦,因为添加了循环并重复了测试初始化​​,否则将完全由其他方法/类构造函数处理。

我的问题是是否有更方便的重试测试机制,比如:

DoSomething();
if (PerformedOK() == false) Retry();
else Assert.Something();

这将自动重试测试而不将其注册为失败,同时照常执行所有常规初始化代码。

最佳答案

说真的...

occasionally DoSomething() performs badly

测试应该每次都是绿色的。如果被测试的代码有时执行得“很差”,那么您需要修复您的代码,隔离不同的行为。您应该有两个测试,一个在 DoSomething 失败(并且应该失败)时断言正确,另一个在 DoSomething 正常(并且应该正常)时断言正确。

在我看来,在测试中使用重试逻辑是错误的。您应该始终对预期结果断言,并且您应该能够隔离和检测您的代码以返回您期望的结果。

[编辑 - 添加了一些可用于重试循环的代码]

你可以创建一个循环包装器,它接受任何方法并调用它 X 次,或者直到它成功。您还可以让 Loop 函数调用您的 init,或将其作为单独的参数传递。如果成功,该方法还可以返回 bool 值。更改签名以满足您的需要。

[TestMethod]
public void something()
{
Loop.LoopMe(TestMethod,3);
Assert.Something();
}

class Loop
{
public static void LoopMe(Action action, int maxRetry)
{
Exception lastException = null;
while (maxRetry > 0)
{
try
{
action();
return;
}
catch (Exception e)
{
lastException = e;
maxRetry--;
}
}
throw lastException;
}
}

关于c# - 重试 Visual Studio C# TestMethod,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3374485/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com