tags:

views:

48

answers:

2

Hi, I'm wondering if there's any mocking framework that allows testing methods contaning method calls to dependent class instances not injected to the tested method or its class:

void MethodToTest()
{
    ....
    DependentClass dc = new DependentClass();
    dc.Foo();
    ....
}

In the code above I would like to mock the call to Foo(). I guess it could be accomplished by a mocking framework using code injection? Thank you in advance for tips.

+3  A: 

I have never used it but based on some articles Moles should be able to do that.

MSDN says:

Mole types use a powerful detouring framework that uses code profiler APIs to intercept calls to dependency classes and redirects the calls to a fake object

Ladislav Mrnka
Thank's, I'll have a look at Mole!
Christian
A: 

If you want to mock the dependent object, you'll need a way to provide a mock instance. The best way to do this is to use dependency injection. It will not only make your code cleaner but it will also help decouple your classes, improving your design.

tvanfosson
Thank's for the answer. Yes, DI is preferable, however in some cases the code might be difficult to refactor and without unit tests in the first place also quite risky.
Christian
"Best way" compared to what? I would argue that the best way would be to use a mocking API which can mock any dependency, whether it's injected or not. Such mocking APIs exist for .NET, Java, Ruby...
Rogerio
@Rogerio - "best way" with regard to improving the design. Encoding the dependency directly in the method makes the method brittle and resistant to change.
tvanfosson
In many cases, *not* encoding the dependency directly only adds unnecessary complexity (an additional field and maybe an extra setter or constructor, and extra DI configuration code), not to mention that it may violate information hiding (by exposing a dependency that otherwise wouldn't be); also, abuse of DI tends to lead to more singletons and less stateful objects (ie, less OO code). Obviously, there is no single best solution for every case. Sometimes DI helps, sometimes not.
Rogerio