Is there a way to use mocks or fakes in your unit tests without having to use dependency injection or inversion or control?
I found this syntax can be used with TypeMock Isolator (http://learn.typemock.com/). It is a comercial product though, so I was hoping that other frameworks (such as RhinoMocks) would be introducing such syntax at some stage.
/// Can mock objects WITHOUT DEPENDENCY INJECTION.
var hand = Isolate.Fake.Instance<Hand>();
var mouth = Isolate.Fake.Instance<Mouth>();
Isolate.Swap.NextInstance<Hand>().With(hand);
Isolate.Swap.NextInstance<Mouth>().With(mouth);
...
//notice we're not passing the mocked objects in.
var brain = new Brain();
brain.TouchIron(iron);
...
This is very attractive to me this type of syntax, it all happens automatically. We can create a brain there with no required dependencies being passed in and the mocking framework will substitute the dependencies automatically for the mock objects. Any body seen this type of thing anywhere else?
The brain class constructor looks like this now using the above syntax,
public Brain()
{
_hand = new Hand();
_mouth = new Mouth();
}
Whereas the dependency injection example would look like this,
public Brain(IHand hand, IMouth mouth)
{
_hand = hand;
_mouth = mouth;
}
Thanks.
If you have a choice, you should almost always expose a constructor to allow dependencies to be injected. You could still keep the convenience constructor (though some would argue that you shouldn’t):
That said, in addition to Isolator you could check out the latest builds of Pex (0.17), which include moles that provide a mechanism similar to Isolator’s
Swap.