How to write CRUD tests for Moq and Linq-to-Sql

I'm just involved in Moq and unit testing, so goodbye if that seems obvious (a quick search through SO showed me nothing like this).

I have an interface with the following suggested member:

void AddFeed(Feed feed);

What I would like to write unit test for this function. 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 to modify the false repository declaration to include this new desired behavior, or should I create another Moq (and how to do it).

My guess is that after creating the layout, getting a unit test will be a lot easier, but the tips will be much appreciated.

Many thanks,

Kevdog

+3
1

, AddFeed,

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

( )

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

, - :

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

, , . , ?

, , , L2Sql , IFeedRepository.

IFeedRepository, - ,

[Test]
public void TheTest()
{
      IFeedRepository repository = Moq.Mock<IFeedRepository>();
      Feed newFeed = new Feed();
      repository.Expect(r => r.Add(newFeed)); //no return as it 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.
}

, , . Moq ,

,

+9

Source: https://habr.com/ru/post/1702919/


All Articles