Search code examples
unit-testingrepositoryrhino-mocks

Unit testing generic repository with rhino mocks


Why is this test failing?

    [TestMethod]
    public void Can_show_next_event()
    {
        // Arrange 

        var eventsRepo = MockRepository.GenerateStub<IRepository<Event>>();

        Event nextEvent = new Event{ 
                                       ID = 2, 
                                       Title = "Test Event", 
                                       Date = DateTime.Now.AddDays(2) 
                                    };

        eventsRepo.Stub(x => x.Find(y => y.Date > DateTime.Now))
                  .Return(nextEvent);

        // Act
        var controller = new EventsController(eventsRepo);
        var result = controller.Index() as ViewResult;

        // Assert
        Assert.IsNotNull(result);
        Assert.AreEqual("Details", result.ViewName);

    }

The test fails on the last line, seem the Repository is not returning what I want it too.

here's the index action

public ActionResult Index()
{
    var model = _eventsRepo.Find(x => x.Date > DateTime.Now);
    return model != null ? View("Details", model) : View("NoEvents");
}

here's my generic repository interface

public interface IRepository<T> where T: class
{
    IQueryable<T> GetAll();
    IEnumerable<T> GetAll(Expression<Func<T, bool>> predicate);
    T GetById(int id);
    T Find(Expression<Func<T, bool>> predicate);
    void Add(T item);
    void Delete(T item);
    void Save();
}

I'm new to mocking with rhino, what am I doing wrong?

Thanks in advance


Solution

  • Try adding .IgnoreParameters() on this line:

    eventsRepo.Stub(x => x.Find(y => y.Date > DateTime.Now))
                      .IgnoreParameters()
                      .Return(nextEvent);
    

    Two side notes: your function "T Find(Expression<Func<T,bool>> predicate)"

    could just use a Predicate<T> instead of a Func<T,bool>. The two are basically the same.

    If you don't already have it, get a copy of the book "The Art of Unit Testing" by Roy Osherove from Manning. http://www.manning.com/osherove/

    He provides several chapters worth of unit testing samples using Rhino.Mocks