Basic Examples

I'll show the code and then explain each part.
public class Program
{
  public static void Main()
  {
    var airplane = ProxyManager.CreateProxy<AirPlane>();

    var flyConfig = ProxyManager.GetAction(airplane.Fly);
    flyConfig.IsReal = false;

    airplane.Fly();

    Assert.AreEqual(1, flyConfig.Count, "Number of times Fly was called");
  }
}

public class Airplane
{
  public virtual void Fly()
  {
    throw new NotImplementedException();
  }
}

First, lets talk about airplanes. My Airplane has a fatal flaw in its design. It was never given the ability to fly. Normally, trying to fly one would crash.

    var airplane = new AirPlane();
    airplane.Fly(); //uh oh

So, in this example, I want to be able to tell my airplane to fly without actually executing it's wayward code. If only I could simulate flight, and not actually try to take the plane off the ground we might have a safer trip.

ProxyManager helps create a proxy of a class. That proxy's methods can then be configured to do, or not do, whatever you want.

ProxyManager.CreateProxy<>()'s template parameter is the proxy type. Here I'm making a proxy of the AirPlane class.

    var airplane = ProxyManager.CreateProxy<AirPlane>();

At last we are ready to fake some methods. Recall that Fly is unsafe, so we're going to put in a simulated Fly method so our plane doesn't blow up when we try to take off. The main thing to understand with these proxies is that every method has its own configuration. If we want to tell the method, Fly, to be fake - to not actually execute its real code (which would crash, remember?), we just need to get the configuration for it and set it to not be real.

    var flyConfig = ProxyManager.GetAction(airplane.Fly);

The configuration object returned by GetAction is a [MethodConfig]. The IsReal property can be used to either have the real code executed when the function is invoked:
    flyConfig.IsReal = true;
Or to run a fake Fly method (which has no body):
    flyConfig.IsReal = false;
This is what we actually did, because our Fly method is unsafe (not literally, http://msdn.microsoft.com/en-us/library/chfa2zb8(VS.71).aspx). Now when we call Fly, the simulation is used, and not the real code!
    airplane.Fly();

The MethodConfigs keep track of lots of interesting things, in this basic example we'll just check the number of times the method was called (just once for this).
    Assert.AreEqual(1, flyConfig.Count, "Number of times Fly was called");

And that's my basic example of using ProxyManager. I hope you liked it. Ready for more?

Last edited Apr 30, 2010 at 7:11 AM by payonel, version 2

Comments

No comments yet.