Testing with PostSharp: make a method just the right amount of unreliable.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// An aspect for use in testing of variable-reliability conditions, by succeeding in calling the | |
/// underlying method only part of the time, returning an exception the rest of the time. | |
/// </summary> | |
[Serializable] | |
public class CallMeMaybeAspect : MethodInterceptionAspect | |
{ | |
private readonly Type exceptionType; | |
private readonly double probability; | |
/// <summary> | |
/// An aspect for use in testing of variable-reliability conditions, by succeeding in calling the | |
/// underlying method only part of the time, returning an exception the rest of the time. | |
/// </summary> | |
/// <param name="probability">The probability that the marked method WILL be called.</param> | |
/// <param name="exceptionType"> | |
/// The exception to be thrown if the method is NOT called (defaults to | |
/// InvalidOperationException). | |
/// </param> | |
public CallMeMaybeAspect (double probability = 0.9, Type exceptionType = null) | |
{ | |
this.probability = probability; | |
this.exceptionType = exceptionType ?? typeof (InvalidOperationException); | |
if (! typeof (Exception).IsAssignableFrom (this.exceptionType)) | |
{ | |
throw new ArgumentException ("Must be a System.Exception or a type derived from System.Exception.", | |
"exceptionType"); | |
} | |
} | |
/// <summary> | |
/// Method invoked <i>instead</i> of the method to which the aspect has been applied. | |
/// </summary> | |
/// <param name="args">Advice arguments.</param> | |
public override void OnInvoke (MethodInterceptionArgs args) | |
{ | |
double chance = (new Random ()).NextDouble (); | |
if (chance < this.probability) | |
args.Proceed (); | |
else | |
{ | |
// Replace with exception. | |
var ex = (Exception) Activator.CreateInstance (this.exceptionType); | |
throw ex; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment