Search code examples
c#unit-testingjustmock

Exception Using PrivateAccessor


I'm trying to set up a simple test to demonstrate how to mock a private method, but when I run it, I get the following exception:

An exception of type 'System.ArgumentException' occurred in mscorlib.dll but was not handled in user code

Additional information: Array may not be empty.

I want to mock GetUsers() in the following class:

public sealed class UserRepository 
{
    private IList<Models.User> GetUsers()
    {
        throw new NotImplementedException();
    }
}

Here is my unit test:

[TestMethod]
public void TestMethod()
{
    //Arrange
    UserRepository userRepo = Mock.Create<UserRepository>(Behavior.CallOriginal);
    IList<User> expected = new User[5];

    Mock.NonPublic.Arrange<IList<User>>(userRepo, "GetUsers").Returns(expected);

    //Act
    var inst = PrivateAccessor.ForType(typeof(UserRepository));
    var users = (IList<User>)inst.CallMethod("GetUsers");  //Error occurs here

    //Assert
    Assert.AreEqual(5, users.Count);
}

Any ideas why I'm getting this error?


Solution

  • GetUsers() in your code is an instance method, whereas PrivateAccessor.ForType() is used only for accessing static members. The best way to create the PrivateAccessor here is

    var inst = Mock.NonPublic.MakePrivateAccessor(userRepo);

    I totally agree that the error message is ridiculous.