Using Method Redirection


Method Redirection is a feature that allows the user to swap two objects that have the same methods signature. The objects do not need to inherit from the same base or implement the same interface for this feature to work. The classes do not need to fully implement the same functionality, only methods that exist on both object shall be redirected.
After the swap is made all calls to the original methods that have matching methods (same signature) will be replaced by the replacing object calls. You can do this by using the Isolate.Swap.CallsOn() method.
Method redirection is useful when you want more complex logic to reside in an object you are replacing (i.e. logging to file, calling an external method etc.).

In the example below we are replacing a duck object with a dog object. If a dog method with same signature of a duck method exist all calls to the duck method will be replaced by calls to the dog method.
[TestMethod]
[Isolated]
public void DuckTypeSwap_ReplaceADuckWithADog()
{
    // Create objects to swap
    var duck = new Duck();
    var dog = new Dog();
   
    // Swap calls on the duck with a dog implementation
    Isolate.Swap.CallsOn(duck).WithCallsTo(dog);
    // The duck object will now go 'Woof!' instead of 'Quack!'
    Assert.AreEqual("Woof!", duck.Talk());

    // It is still a duck in every aspect that a dog can't do
    duck.LayEgg();
    Assert.AreEqual(1, duck.EggCount);

    // Even though duck calls are now redirected to dog calls, we can still verify the duck calls are made
    duck.Walk();
    Isolate.Verify.WasCalledWithAnyArguments(() => duck.Walk());
}

// classes being swapped
public class Duck
{
    public void Walk()
    {
        Waddle();  
    }

    public string Talk()
    {
        return "Quack!";
    }

    public void LayEgg()
    {
        eggCount = EggCount + 1;
    }

    public int EggCount
    {
        get { return eggCount; }
    }

    private int eggCount = 0;

    private void Waddle()
    {
    }
}

public class Dog
{
    public void Walk()
    {
        ChaseCar();
    }
   
    public string Talk()
    {
        return "Woof!";
    }

    private void ChaseCar()
    {
    }
}



If there are no matching methods between the two types the Isolator will throw TypeMockException.
When a method in the original class invoked and the target class does not have a method with the same signature the original method is called. You can see this behavior in the above example when duck.LayEgg is called.
If you only need to redefine one method's behavior to custom behavior, use Isolate.WhenCalled().DoInstead()

Copyright © Typemock Ltd. 2004-2009. All Rights Reserved.