Extension methods are not good for testing (that's described here: Mocking Extension Methods with Moq, http://www.clariusconsulting.net/blogs/kzu/archive/2009/12/22/Howtomockextensionmethods.aspx).
But probably there are some solutions for mocking of Unity methods? In my case I have the following function:
public class MyManager
{
public MyManager(IUnityContainer container) : base(container) { }
public IResult DoJob(IData data)
{
IMyLog log = MyContainer.Resolve<IMyLog>();
... use log.Id ...
MyContainer.Resolve<...>();//usage for other purposes...
}
I want to be sure that 'DoJob' method will always get 'IMyLog' object from container, but not from other sources... how could I test that?
My original idea was to change 'DoJob' method implementation and use:
IMyLog log = UnityContainer.Resolve(typeof(IMyLog)) as IMyLog;
But 'Resolve(Type t, ...)' is also an extension method...
Any thoughts are welcome.
P.S. Please note, that 'my log' object is created far-away from MyManager.DoJob...
I know I'm late to the party, but I had the same problem, and resolved it by mocking out the following method -
For example -
Just in case someone needs to mock this out and can't remove the dependency on the container.
Guess, I found most appropriate solution for test: It is not necessary to mock unity container and check if 'log' object was taken from it. I will just make a mock for 'Log' object, register its object instance in the container and check in test if this log object is really used.
This will do what is required.
Thanks.
Remove the dependency on IUnityContainer and things become a lot easier and cleaner. Instead let unity inject your dependencies which are abstracted into interfaces. These are easily mocked. Here's an example using a little trick with Unity that injects an auto-factory for IMyLog.
Or if you don't need to create the instance each time:
I will have to disagree with both answers. TheCodeKing, it is entirely legitimate to use IoC interface directly. One example might be a controller factory in ASP.NET project - where one might do non-trivial resolution using multiple methods onIUnityContainer
interface.Hmm... with auto-factory injecting labdas, one never has to unit test the IoC interface directly. You could just pass a lambda and verify that it gets called with the right parameters.
Budda, you should never bring in an IoC container into your unit test. The dependencies must be injected manually.
Below is the solution I use. I basically created a layer of abstraction over
IUnityContainer
and implemented a simple class that delegates toIUnityContainer
. Because my interface does not contain extension methods, I can easily mock it.Now, rewrite your class to use
IDIContainer
:And rewrite the unit test like so: