Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 247
Jake Stevenson Avatar asked Jun 28 '10 15:06

Jake Stevenson


2 Answers

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.

like image 85
Mark Seemann Avatar answered Oct 22 '22 21:10

Mark Seemann


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.

like image 33
Artem G Avatar answered Oct 22 '22 23:10

Artem G