matthiasgh
matthiasgh

Reputation: 321

When a TestMethod fails repeat once

I'm writing coded UI test's for an ASP.NET MVC web application. I'm using Visual Studio 2012.

Basically I have a bunch of test methods like below:

Enter image description here

I use a ordered test file to run all of them at once in the order I would like.

The problem is that the way the tests work is that if one test fails, it is marked as ref/failed in the output, and often a test will work if I run it again. I want to be able to set my ordered test to run and if a test method fails it will automatically try to run that test method one more time.

How do I do this? I was thinking of putting an if statement at the end of each test method, like:

if(TestFailed) {
    RecallTest();
}

I would use some sort of counter, but how do I write the above in a coded UI test?

Upvotes: 0

Views: 162

Answers (2)

barakcaf
barakcaf

Reputation: 1324

Try using the playback error handling:

 Playback.PlaybackError += Playback_PlaybackError;

This way you can register an event handler that is called every time the playback encounters an error.

In the event handling method you can tell the playback to repeat the action that threw the error:

static void Playback_PlaybackError(object sender, PlaybackErrorEventArgs e)
{                              
    e.Result = PlaybackErrorOptions.Retry;
}

A counter can be added to prevent an endless loop of error and retry.

Upvotes: 1

Kate Paulk
Kate Paulk

Reputation: 383

There are several ways you can handle this. The most obvious is something like this:

[TestMethod]
public void myTestMethod()
{
    int iteration = 0;
    if (iteration < 2)
    {
       try
       {
           // the usual test code goes here
       }
       catch (Exception)
       {
            // handles any exception kind
            iteration++;
            myTestMethod(); 
       }
    }
}

This will recursively call the test method only if the method fails. You can set it to catch any exception (Exception) or to catch specific exceptions only - just change the exception kind in the catch block.

This is typically discouraged in CodedUI tests because it can interact badly with the test runner's built in exception reporting (I'd recommend looking at adding logging to report that you got a failure). It will give you the one-time only rerun, however (Caveat: I haven't actually tried this myself - you might need to tweak the code to ensure that your test cleanup occurs depending on your test code).

Upvotes: 2

Related Questions