Nathan
Nathan

Reputation: 6531

Intercept Method/Property call in c#

In the code below I have a class Foo which is called (without an interface) by my main method. There is no backing field or setter for the property, instead it calls a private method. Foo cannot be changes, nor can the usage of foo be changed to an IFoo interface.

- How do I change the value of foo.FooValue?

- Is there anything in the System.Reflection, System.Reflection.Emit, .NET standard libraries etc (unsafe code, whatever) that I can include in a unit test to change the return value?

I appreciate if there is something it's bound to be quite "evil", but I am interested in "evil" answers.

public class Program
{   
    public static void Main(){

        Foo foo = new Foo();
        int bar = foo.FooValue;
    }
}

public class Foo{

    public int FooValue
    {
        get
        {
            return this.FooMethod();
        }
    }

    private int FooMethod
    {
         return 0;
    }
}

Related questions:

How to set value of property where there is no setter - Related but unanswered - Maybe the answer is "no", but I'm not convinced by the top answer which merely points out you can't achive this by changing a (non-existent) backing field.

Intercept call to property get method in C# - Interesting. Not sure whether this is my answer and if it is, not sure how it could be used in a unit test.

EDIT: Okay. I'm going to re-write my code to make it more testable. However, out of interest, has anyone out there successfully hacked their way through this situation?

Upvotes: 0

Views: 1586

Answers (1)

D Stanley
D Stanley

Reputation: 152624

You could create a proxy for Foo that could be mocked:

public class FooProxy : IFoo
{
    private Foo _Foo;
    public FooProxy(Foo foo)
    {
        _Foo = foo;
    }
    public int FooValue
    {
        get {return _Foo.FooValue();
    }
}

public interface IFoo
{
    public int FooValue {get;}
}

then you can use DI to "inject" an IFoo and make your code more testable.

Upvotes: 3

Related Questions