سؤال

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?

هل كانت مفيدة؟

المحلول

This code allowed me to mock the coupled dependency:

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

Remember, TypeMock supports very few types from mscorlib.

نصائح أخرى

Declaimer I work at Typemock.

Swapping instances is obsolete for a while now. You can use:

var fakeFoo = Isolate.Fake.NextInstance<Foo>();

fakeFoo is a proxy to _foo in your code.

You can also use:

var fakeFoo = Isolate.Fake.AllInstances<Foo>();

Here fakeFoo is a proxy to all the instances of Foo that created (new) from this line on.

Both examples create a fake and "swap" it in one command.

First, when working with the TypeMock Isolatar API, I highly recommend you have this PDF by your side: TypeMock Isolator API Quick Reference(PDF)

With respect to the point above, yes I find it a common mistake that creating a fake does not mean it gets used. Like you pointed out above, in order to use it you must do something like:

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

This will swap the next instance. I am pretty sure you can also do:

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

This will swap the next object creation with the FooFake instance, and then the one after that with FooFake2

You can also do this:

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

This will swap ALL future object creation with the fake. This is very useful if you are looking at code where it may not be obvious how many times object creation will happen.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top