Search code examples
c#model-view-controllerunit-testingrhino-mocks

How to mock inherited methods


Im trying to mock a method that is ineherited from a parent class that is generic. Right know my code looks like this.

public interface IBaseRepository<T>
{
    IEnumerable<T> FindMany(Func<T, bool> condition);
}

public interface IPersonRepository : IBaseRepository<person>
{
    //Here I got some specifics methods for person repository
}

My test code looks like this;

    private IPersonRepository mockPersonRepository { get; set; }

    [TestMethod]
    public void TestMehtod()
    {
        LogonModel model = CreateLogonModel("test@test.com", "test", "Index");
        person p = new person() { Email = model.Email, password = model.Password, PersonId = 1 };

        mockPersonRepository.Stub(x => x.FindMany(y => y.Email == model.Email && y.password == model.Password)).Return(new List<person> {p});
        mockPersonRepository.Replay();

        var actual = instanceToTest.LogOnPosted(model) as PartialViewResult;

        Assert.AreEqual("_Login", actual.ViewName);
    }

When I am using the debugging tool in vs 2010 I can se that me Stub, doesnt works, the return person is always null. I have declared the FindMany method as virtual.

Does anybody know how to stub that method? Im using RhinoMocks.


Solution

  • The problem is that you are comparing the lambda - but you are really interested in having the person instance passed into the lambda match your person object based on satisfying the predicate condition - You can use Matches() to achieve this by just executing the predicate on p - if that equates to true than you have a match and should return the stubbed list:

    mockPersonRepository.Stub(x => x.FindMany(Arg<Func<person, bool>>.Matches( y => y(p))))
                        .Return(new List<person> { p });