我有一个CodedUI测试。它通过异常零星失败(无法关注元素)。我可以做这样的事吗
[TestMethod]
public void MySporadicFailedTest()
{
try {
//Some Test action
}
catch((Exception ex)) {
if (ex is System.Exception.ElementNotFocused){
//retry test
}
}
}
答案 0 :(得分:1)
这是我在编写编码UI测试时经常处理的问题。我几乎总是写一个简单的扩展方法来处理重试特定的动作(而不是整个测试!)。有时候,特别是在有奇怪的,非标准的标记或许多AJAXy事件发生的页面上,你只会遇到一个动作会因为某些事情尚未准备就会失败的情况,然后通过下一个动作。
public static class TestRetryExtensions
{
public static void WithRetry<T>(this Action thingToTry, int timeout = 30) where T: Exception
{
var expiration = DateTime.Now.AddSeconds(timeout)
while (true)
{
try
{
thingToTry();
return;
}
catch (T)
{
if (DateTime.Now > expiration)
{
throw;
}
Thread.Sleep(1000);
}
}
}
}
然后,在我的实际测试中:
uiMap.ClickSomeThing();
uiMap.EnterSomeText();
Action clickSomeOtherThingAction = () => uiMap.ClickSomeOtherThingThatFailsForNoReason();
clickSomeOtherThingAction.WithRetry<UITestControlHiddenException>(60);
尝试执行操作。如果它失败并且您不知道偶尔会出现“正常”事件,它会正常抛出异常。如果它失败并且你要告诉它重试,它将继续尝试该操作(重试之间有1秒的延迟),直到超过超时,此时它只是放弃并重新抛出异常。
答案 1 :(得分:0)
只要您可以捕获抛出的异常,就可以将测试代码包装在重试循环中。然后它会在放弃之前尝试测试代码一定次数:
for (var i = 0; i < TimesToRetry; i++)
{
try{
//perform test
//test ran correctly - break out loop to end test
break;
}
catch(Exception){
//might want to log exception
}
}
答案 2 :(得分:0)
如果编码的测试在没有正当理由的情况下连续失败,您可以添加一些代码来增强测试并使其安全失败。如果在聚焦到元素时测试失败,则首先尝试将焦点放在上层元素上,然后尝试聚焦子元素。这个LINK可以帮助您编写故障安全测试用例。
答案 3 :(得分:0)
we can include below line of code in test clean up method to re run the failed script
if (TestContext.CurrentTestOutCome==TestContext.unittestoutcome.failed)
{
var type=Type.GetType(TestContext.FullyQualifiedTestClassName);
if (type !=null)
{
var method=Type.GetMethod(TestContext.TestName);
var event=Activator.CreateInstance(type);
}
method.invoke(event);
}