C# 在try-catch块中出现异常时重试
我试图复制一个场景,如果捕获到异常,代码应该重新运行一定次数C# 在try-catch块中出现异常时重试,c#,C#,我试图复制一个场景,如果捕获到异常,代码应该重新运行一定次数 using System; using System.Threading; public class Program { public static void Main() { MyClass myClass = new MyClass(); Console.WriteLine(myClass.MyMethod(5)); } } public class MyClass {
using System;
using System.Threading;
public class Program
{
public static void Main()
{
MyClass myClass = new MyClass();
Console.WriteLine(myClass.MyMethod(5));
}
}
public class MyClass
{
public Test(){}
public string MyMethod(int tryCount) {
while(tryCount > 0)
{
// some logic that returns the switchType
// in this case i'm just manually setting it to 1
int switchType = 1;
try {
switch(switchType)
{
case 1:
return "it worked!!!";
case 2:
break;
}
} catch (Exception e){
if (--tryCount == 0) throw new Exception("Failed");
}
}
return null;
}
}
如何强制它进入catch块,以便测试重试逻辑是否正常工作?您可以在测试时手动从代码中抛出异常
throw new Exception("Your custom message");
对你的问题最简单的回答就是抛出一个新的异常 但你可能也希望能够测试快乐之路 下面是我要做的:
using System;
using System.Threading;
public class Program
{
public static void Main()
{
// what happens when no problem
MyClass.happyPath = true;
MyClass myClass = new MyClass();
Console.WriteLine(myClass.MyMethod(5));
// does the retry work?
MyClass.happyPath = false;
MyClass myClass = new MyClass();
Console.WriteLine(myClass.MyMethod(5));
}
}
public class MyClass
{
public static boolean happyPath = true;
public Test(){}
public string MyMethod(int tryCount) {
while(tryCount > 0)
{
// some logic that returns the switchType
// in this case i'm just manually setting it to 1
int switchType = 1;
try {
switch(switchType)
{
case 1:
if (!happyPath) {
throw new Exception ("Oops, it didn't work!");
}
return "it worked!!!";
case 2:
break;
}
} catch (Exception e){
if (--tryCount == 0) throw new Exception("Failed");
}
}
return null;
}
}
在break语句中添加的抛出应该被catch捕获,它允许您检查重试逻辑。建议您添加一些日志记录。不太可能,因为在我的情况下,为了测试起见,我想强制执行一个异常。可能是在代码中生成的switchType比您想要捕获的要多,不是吗?没有办法,带int的简单开关将引发异常。。。因此,没有办法或理由对其进行测试。如果您有可能引发异常的内容,例如someClass.DoSomething。。然后您可以模拟该部分,例如someClassMock.Setupmock=>mock.DoSomething.throwsnewException@vc74这是有道理的,我将充实它以触发异常。此外,这是我的重试逻辑声音?这正是我要找的。谢谢另一方面,你觉得我的重试逻辑合理吗?