views:

24

answers:

1

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?

A: 

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.

Mark Seemann
Thank you very much for the tip, it works perfectly.
Jake Stevenson