Thursday, August 23, 2012

Testing Transient errors in Azure

It is a bit difficult to generate a genuine throttling exception for testing purposes. But we can easily create fakes.
Create a mock class derived from ITransientErrorDetectionStrategy and return true(IsTransient). Use this class in
 var retryPolicy = new RetryPolicy<MockClass>(retryStrategy);  
Throw any exception in code and that is it, it retries!
If needed the ITransientErrorDetectionStrategy can be injected for unit testing.

ITransientErrorDetectionStrategy implementation is described in this class diagram and for more reading here

//------------------Code-
 
using Microsoft.Practices.TransientFaultHandling;
using Microsoft.Practices.EnterpriseLibrary.WindowsAzure.TransientFaultHandling;
...
// Define your retry strategy: retry 5 times, starting 1 second apart
// and adding 2 seconds to the interval each retry.
var retryStrategy = new Incremental(5, TimeSpan.FromSeconds(1), 
  TimeSpan.FromSeconds(2));
// Define your retry policy using the retry strategy and the Windows Azure storage
// transient fault detection strategy.
var retryPolicy =
  //new RetryPolicy<StorageTransientErrorDetectionStrategy>(retryStrategy);
new RetryPolicy<TransientMock>(retryStrategy);
// Receive notifications about retries.
retryPolicy.Retrying += (sender, args) =>
    {
        // Log details of the retry.
        var msg = String.Format("Retry - Count:{0}, Delay:{1}, Exception:{2}",
            args.CurrentRetryCount, args.Delay, args.LastException);
        Trace.WriteLine(msg, "Information");
    };
try
{
  // Do some work that may result in a transient fault.
  retryPolicy.ExecuteAction(
    () =>
    {
        // Call a method or write on or more statements that uses Windows Azure storage and which  may
        // throw a transient exception. 
       //for the mock to work throw any exception
       throw new Exception();
        this.queue.CreateIfNotExist();
    });
}
catch (Exception)
{//exceptions not caught by transient framework comes here
  // All the retries failed.
}



//==========================
public class TransientMock : ITransientErrorDetectionStrategy
{
 public bool IsTransient(Exception ex)
        {
  return true;
        }
} 
~comment your thoughts, please~

No comments:

Post a Comment

Post a Comment