Question

Scratching my head how to do this.

Suppose I had a concrete class Foo with 2 virtual methods, Execute() and GetFile(). Execute() will call GetFile. I want to make sure that when it does, GetFile() will throw a couple of different exceptions that Foo is supposed to handle gracefully in a testable manner.

For my unit tests, I am envisioning instantiating a DynamicProxy<Foo> from castle project where I intercept the GetFile() to throw the exception, and then invoke the DynamicProxy object's Execute() method, and test the results, but I can't see how to do this.

Is this possible/ practical? If so, what would the creation of the dynamic proxy object look like?

Was it helpful?

Solution

You don't need to handcode your own proxy because most the mocking frameworks support your scenario.

Here is an example using Moq (Moq will create a dynamic proxy internally for you):

public class SomeException : Exception { }

public class Foo
{
    public virtual int Execute()
    {
        try
        {
            GetFiles();
        }
        catch (SomeException)
        {
            return 1;
        }
        return 0;
    }

    public virtual void GetFiles()
    {
        //...
    }
}

[Test]
public void FooTest()
{
    var fooUnderTest = new Mock<Foo>();
    fooUnderTest.CallBase = true;
    fooUnderTest.Setup(f => f.GetFiles()).Throws(new SomeException());
    var result = fooUnderTest.Object.Execute();
    Assert.AreEqual(1, result);
}

You just need to take care to set Callbase = true which will:

Invoke base class implementation if no expectation overrides the member (a.k.a. "Partial Mocks" in Rhino Mocks): default is false.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top