在运行时重新运行CodedUI测试
本文关键字:测试 CodedUI 重新运行 运行时 | 更新日期: 2023-09-27 18:25:22
我有一个CodedUI测试。它偶尔会因异常而失败(无法聚焦元素)。我能做一些类似的事情吗
[TestMethod]
public void MySporadicFailedTest()
{
try {
//Some Test action
}
catch((Exception ex)) {
if (ex is System.Exception.ElementNotFocused){
//retry test
}
}
}
这是我在编写编码UI测试时经常遇到的问题。我几乎总是写一个简单的扩展方法来处理重试特定的操作(而不是整个测试!)。有时,尤其是在有奇怪、非标准标记或大量AJAX事件发生的页面上,您只会遇到一种情况,即某个操作前一秒会失败,因为某些东西还没有准备好,然后再通过下一秒。
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秒的延迟),直到超过超时为止,此时它就会放弃并重新引发异常。
只要您能够捕获抛出的异常,就可以将测试代码封装在重试循环中。然后它会在放弃之前尝试测试代码一定次数:
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
}
}
如果codedUI测试在没有正当理由的情况下持续失败,您可以添加一些代码来增强测试并使其故障安全。如果测试失败,特别是在聚焦到一个元素时,请尝试先聚焦到上层元素,然后再尝试聚焦子元素。此链接可以帮助您编写故障安全测试用例。
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);
}