bryan
bryan

Reputation: 1051

Mocking a Repository returning a list

I'm beyond lost in the woods at this point, I keep making the same changes over and over with the thought that intellisense is just hiding something from me.

I'm trying to create a mocked repo to test adding (and querying) single types and lists. the single repo is working as:

public Mock<IBaseRepository<DNS_Entity>> RepositoryFakeObject()
    {
        var _dns = new List<DNS_Entity>();
        var mock = new Mock<IBaseRepository<DNS_Entity>>();

        mock.Setup(x => x.Add(It.IsAny<DNS_Entity>()))
            .Callback((DNS_Entity e) => _dns.Add(e));

        mock.Setup(x => x.SelectALL()).Returns(_dns.AsQueryable());
        return mock;
    }

However, my attempts to do something similar for a list are just not working. Specifically the Returns in the Setup is laughing at me.

What I have at this point is:

 public Mock<IBaseRepository<List<DNS_Entity>>> RepositoryFakeList() // Mock<IBaseRepository<List<DNS_Entity>>>
    {
        var _dns = new List<DNS_Entity>();
        var mock = new Mock<IBaseRepository<List<DNS_Entity>>>();

        mock.Setup(x => x.Add(It.IsAny<List<DNS_Entity>>()))
            .Callback((List<DNS_Entity> le) => _dns.Add(le.Select(e => e) as DNS_Entity));

       // mock.Setup(x => x.SelectALL()).Returns((IQueryable<List<DNS_Entity>>) (_dns));

        mock.Setup(x => x.SelectALL()).Returns(_dns.AsQueryable());
        return mock;

    }

Ultimately I'd like to do something with an add test like:

[Test]
    public void AddNewList()
    {
        var mock = RepositoryFakeList();

        var lst = new List<DNS_Entity>
                      {
                          new DNS_Entity {FirstName = "added", LastName = "From Test"},
                          new DNS_Entity {FirstName = "added2", LastName = "From Test2"}
                      };

        mock.Object.Add(lst);

        Assert.IsTrue(mock.Object.SelectALL().Count() == 2);
    }

What am I missing here? I have never mocked a repo like this before, so I've probably violated some basic tenets, and if so please let me know.

Thanks.

Upvotes: 2

Views: 1699

Answers (1)

aqwert
aqwert

Reputation: 10789

I think the issue is with this line

.Callback((List<DNS_Entity> le) => _dns.Add(le.Select(e => e) as DNS_Entity));

When you use Select it returns an IEnumerable<DNS_ENTITY> but you are casting it to DNS_ENTITY which will result in null

try...

.Callback((List<DNS_Entity> le) => _dns.AddRange(le));

Upvotes: 4

Related Questions