开发者

Using Moq with Windsor -- Object of Type Moq.Mock[IFoo] cannot be converted to IFoo

I'm trying to set up some Moq repositories to test my service with Castle Windsor as my IOC. Mu service depends on IFoo, so I'm creating a moq instance 开发者_如何学编程that implements IFoo and injecting it into the container like so:

_container.AddComponent("AutoBill", 
  typeof (AutoBillService), typeof (AutoBillService));

var mockUserRepository = new Mock<IUserRepository>();
var testUser = new User()
   {
     FirstName = "TestFirst",
     LastName = "TestLast", 
     UID=1
   };
mockUserRepository.Setup(repo => repo.GetUser(testUser.UID))
   .Returns(testUser);

_container.Kernel.AddComponentInstance("UserRepository", 
   typeof(IUserRepository), mockUserRepository);

var service = _container.Resolve<AutoBillService>(); //FAIL

Doing this gives me an exception: System.ArgumentException: Object of type 'Moq.Mock`1[IUserRepository]' cannot be converted to type 'IUserRepository'

Can anyone see what I'm doing wrong?


You should pass mockUserRepository.Object instead of mockUserRepository.

This would be a lot more evident if you used the strongly typed API:

_container.Register(Component
    .For<IUserRepository>()
    .Instance(mockUserRepository.Object));

This compiles because the Object property implements IUserRepository.


I head the same problem with Castle Windsor. A dinamyc initialization with method:

container.Register(Component.For<IUserRepository>()
         .Instance(mockUserRepository.Object));

didn't work until I removed from my caslteRepository.config file pre-initialized repositories (like your IUserRepository) and left container "empty" from repositories.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜