chevron-thin-right chevron-thin-left brand cancel-circle search youtube-icon google-plus-icon linkedin-icon facebook-icon twitter-icon toolbox download check linkedin phone twitter-old google-plus facebook profile-male chat calendar profile-male
0 votes
Hi

is there a way I can fake an instance, and "add" functionality to a specific method?

For example, in the following I'd like to swap instances of "MyClass" with a fake, but actually only replace the method "MyMethod" with a fake method which actually performs a bit of extra checking for my test, and then calls on to the real instance method to complete processing.

MyClass mc = Isolate.Fake.Instance<MyClass>(Members.CallOriginal);
Isolate.WhenCalled(() => mc.MyMethod(null)).
    DoInstead((callContext) =>
    {
        // do some special test/check stuff....
        // call real instance MyMethod and return its value...
    });
Isolate.Swap.AllInstances<MyClass>().With(mc);


Thanks, Peter
asked by xdzgor (3.3k points)

3 Answers

0 votes
It appears I can do the following. Can anyone verify that this is ok?

MyClass mc = Isolate.Fake.Instance<MyClass>(Members.CallOriginal);
Isolate.WhenCalled(() => mc.MyMethod(null)).
    DoInstead((callContext) =>
    {
        // do some special test/check stuff.... (to-do)

        // Call the real instance method:
        MyParam p = callContext.Parameters[0] as MyParam;
        MyClass real = callContext.Instance as MyClass;

        MyResult result = real.MyMethod(p);
        return result;
    });
Isolate.Swap.AllInstances<MyClass>().With(mc);
answered by xdzgor (3.3k points)
0 votes
Hi Peter,

Yes you can do it, but note that MyMethod will faked two times before the real method will run.
The real value that you create in the call back will be faked the first time because you stated that you want to swap all instances of MyClass, this will cause faking of the instance you create in the callback. Only than the Isolator will mark the next call as not fake and will let you call your real implementation.
answered by ohad (35.4k points)
0 votes
A better way might be to save the values you want to test and assert them after the run. (arrange. Act. Assert)
In any case there is a hack to return TypeMock.MockManager.continue_with_method that will call the original code.
answered by eli (5.7k points)
...