views:

1260

answers:

1

I am just getting involved in Moq and unit testing, so forgive me if this seems obvious (a quick search through SO didn't show me anything like this).

I have an interface with the following proposed member:

void AddFeed(Feed feed);

That I would like to write a unit test for this functionality. The test class has a Moq Repository declared as follows:

static IFeedRepository MockFeedsRepository(params Feed[] feeds)
    {
        var mockFeedsRepository = new Moq.Mock<IFeedRepository>();
        mockFeedsRepository.Expect(x => x.Feeds).Returns((feeds.AsQueryable));

        return mockFeedsRepository.Object;
    }

How should the mock repository declaration be modified to include this new desired behavior or should I create a different Moq (and just how would that be done).

My assumption is that after creating the mock, deriving the unit test will be much easier but hints are greatly appreciated.

Many thanks,

KevDog

+8  A: 

I'm also assuming that you would use the AddFeed method like this

Feed myNewFeed = new Feed();
feedRepository.Add(myNewFeed);

and that you're not using it like this (which is poor design)

IFeedRepository feedRepository = new FeedRepository();
Feed myNewFeed = new Feed(feedRepository);
...
myNewFeed.Save();

I'm going to guess that you would want to then have a test something like this:

[Test]
public void TheTest()
{
  IFeedRepository repository = MockFeedsRepository({feed1, feed2, feed3});
  Feed newFeed = new Feed();
  repository.Add(newFeed);
  Assert.AreEqual(4,repository.Count());
}

If that's the case then the test isn't actually testing anything other than your implementation of a mock in-memory repository. Is that what you really need to be doing?

I'd suggest that what you want to be doing is testing the L2Sql implementation of the repository instead, or testing how classes interact with the IFeedRepository interface.

And if you want to test the usage of the IFeedRepository interface then just do something simple like

[Test]
public void TheTest()
{
      IFeedRepository repository = Moq.Mock<IFeedRepository>();
      Feed newFeed = new Feed();
      repository.Expect(r => r.Add(newFeed)); //no return as it's a void method
      //repository.Expect(r => r.Add(newFeed)).Throws(new ApplicationException()); --Test handing of exceptions

      //Code to hit the .Add() method

      //Assert the Add method was called.
}

For tips on asserting if a method was called, see http://stackoverflow.com/questions/347818/using-moq-to-determine-if-a-method-is-called

I hope that helps

Richard Banks
Your assumption on how I am using the AddFeed method is correct. I did end up writing a test for the Linq-to-Sql parts, just as you suggested, as it seemed I was testing the wrong parts. Thanks for clearing up my confusion.
KevDog