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

江枫思渺然 提交于 2019-12-12 12:23:10

问题


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?


回答1:


This code allowed me to mock the coupled dependency:

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

Remember, TypeMock supports very few types from mscorlib.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/9978273/typemock-isolator-mock-a-dependency-thats-not-injected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!