constructormockingdependenciestypemocktypemock-isolator

Typemock Isolator: Mock a dependency that's not injected?


My WidgetDoer class depends on Foo, which is not injected. I need to fake _foo's implementation of DoStuffWith() (and then verify that Do() returned the result -- this is a simplified representation of my real code).

public class WidgetDoer {
    readonly Foo _foo;

    public WidgetDoer() {
        _foo = new Foo();
    }

    public Bar Do(Widget widget) {
        var result = _foo.DoStuffWith(widget);
        return result;
    }
}

I tried to use the following Isolator syntax to prevent a real Foo object from being created (inside the WidgetDoer() constructor), but the real Foo object is instantiated anyway:

var fooFake = Isolate.Fake.Instance<Foo>();
Isolate.WhenCalled(() => new Foo()).WillReturn(fooFake);

Can I use Typemock to mock a dependency which is not injected?


Solution

  • This code allowed me to mock the coupled dependency:

    Isolate.Swap.NextInstance<Foo>().With(FooFake);
    

    Remember, TypeMock supports very few types from mscorlib.