mardi 21 juin 2016

EF Mock of dbContext dont use eager loading

I try to use NUnit and Moq to unit test a service, which access data. I create Mock of DbContext like this:

My entities and context

 public class BloggingContext : DbContext
{
    public virtual DbSet<Blog> Blogs { get; set; }
    public virtual DbSet<Post> Posts { get; set; }
}

public class Blog
{
    public int BlogId { get; set; }
    public string Name { get; set; }
    public string Url { get; set; }

    public virtual List<Post> Posts { get; set; }
}

public class Post
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }

    public int BlogId { get; set; }
    public virtual Blog Blog { get; set; }
}

Test method:

public void CreateBlog_saves_a_blog_via_context()
    {
       var data = new List<Blog>
        {
            new Blog { Name = "BBB" },
            new Blog { Name = "ZZZ" },
            new Blog { Name = "AAA" },
        }.AsQueryable();

        var data2 = new List<Blog>
        {
            new Post{ Title= "BBB" },
            new Post{ Title= "ZZZ" },
            new Post{ Title= "AAA" },
        }.AsQueryable();

        var mockSet = new Mock<DbSet<Blog>>();
        mockSet.As<IQueryable<Blog>>().Setup(m => m.Provider).Returns(data.Provider);
        mockSet.As<IQueryable<Blog>>().Setup(m => m.Expression).Returns(data.Expression);
        mockSet.As<IQueryable<Blog>>().Setup(m => m.ElementType).Returns(data.ElementType);
        mockSet.As<IQueryable<Blog>>().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator());

        var mockSet2 = new Mock<DbSet<POs>>();
        mockSet2.As<IQueryable<Blog>>().Setup(m => m.Provider).Returns(data2.Provider);
        mockSet2.As<IQueryable<Blog>>().Setup(m => m.Expression).Returns(data2.Expression);
        mockSet2.As<IQueryable<Blog>>().Setup(m => m.ElementType).Returns(data2.ElementType);
        mockSet2.As<IQueryable<Post>>().Setup(m => m.GetEnumerator()).Returns(data2.GetEnumerator());

        var mockContext = new Mock<BloggingContext>();
        mockContext.Setup(c => c.Blogs).Returns(mockSet.Object);
        mockContext.Setup(c => c.Posts).Returns(mockSet2.Object);
        var service = new BlogService(mockContext.Object);
        var blogs = service.GetAllBlogs();
    }

But when I wont to set relational between entities I test them

Post = new Post(){
  Title ="",
  Content = "",
  BlogID = 2
};

But navigation property don't set in the test(In the normal setup its setups). When I try to read this post from context I always have null, but BlogID is already set.

Aucun commentaire:

Enregistrer un commentaire