问题
I have a running code with unity.
Now I want to use Moq to do my unit testing for ASP-MVC. In the global.asax's code, I have the following:
IUnityContainer container = new UnityContainer();
container.RegisterType<IFoo, Foo>(new InjectionConstructor("xxx"));
Now I wrote testcode with Moq:
IUnityContainer container = new UnityContainer();
var mockFoo = new Mock<IFoo>();
container.RegisterType<IFoo, mockFoo) >(new InjectionConstructor("xxx"));
but this don't work.
Error: The type 'Moq.Mock' cannot be used as type parameter 'TTo' in the generic type or method 'Microsoft.Practices.Unity.UnityContainerExtensions.RegisterType... There is no implicit reference conversion from 'Moq.Mock' to 'IFoo'
回答1:
You are trying to register the mock-object, not the mocked-object.
var mock = new Mock<IFoo>();
container.RegisterInstance<IFoo>(mock.Object);
来源:https://stackoverflow.com/questions/12614703/how-to-use-unity-registertype-with-moq