开发者

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", r开发者_StackOverflow中文版esult.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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜