tags:

views:

247

answers:

1

I have an interface named IAuthorizationRepository with the following interface:

public interface IAuthorizationRepository
{
 IQueryable<User> Users { get; }

 Int32 SaveChanges();

 void Detach(Object entity);
 void Attach(IEntityWithKey entity);

 void DeleteObject(Object entity);
 void AddObject(String entitySetName, Object entity);
}

Where User is defined as follows:

public class User{
string Username { get; set; }}

And I have a TestInitialize method like this:

    [TestInitialize]
 public void Init()
 {
  _repository = new Mock<IAuthorizationRepository>();

  List<User> users = new List<User>();

  User user = new User();
  user.Username = "test_osness";

  _repository.ExpectGet(r => r.Users).Returns(users.AsQueryable());

  _repository.Expect(r => r.AddObject("Users", It.IsAny<Object>()))
   .Callback<User>(u => users.Add(u));

  _repository.Object.AddObject("Users", user);

  Console.WriteLine("Users: {0}", _repository.Object.Users.Count());
 }

But when I run the test I am getting a System.Reflection.TargetParameterCountException on the line which calls _repository.Object.AddObject("Users", user). I'm new to Moq, but from what I can tell this should work. What am I doing wrong. I want to add a user object to my List when AddObject("Users" , Object) is called. So _repository.Object.Users.Count() should reflect that the correct number of users.

A: 

I'm gonna overwrite my previous answer.

This line:

_repository.Expect(r => r.AddObject("Users", It.IsAny<Object>()))
    .Callback<User>(u => users.Add(u));

Is looking to call a version of .Callback() that takes a single parameter. However, your "AddObject" method that you're expecting takes two parameters. I think you need something more like this:

_repository.Expect(r => r.AddObject("Users", It.IsAny<Object>()))
    .Callback((s, o) => users.Add(o as User));

Now the Callback lambda takes the same number of parameters as your expectation, so it should work.

Matt Hamilton