简体   繁体   中英

How to use Moq with Entity Framework Include()

I am trying write unit test for my DAL layer.

The complication is that the DAL Layer has a query which uses Include().

I don't know how to mock the Include() method.

Models

    public class Apps
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        [DataMember]
        public int ID { get; set; }

        [DataMember]
        [Required(ErrorMessage = "App name required.")]
        public string Name { get; set; }

        public virtual ICollection<AppDataPermission> AppDataPermissions { get; set; }

    }

public class AppDataPermission{
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        [DataMember]
        public int ID { get; set; }

        public DataPermissions DataPermission { get; set; }

        public virtual Apps App { get; set; }
    }

public enum DataPermissions 
{
        Admin = 1,
        Support = 2
    }

DAL

public List<Apps> GetApps()
        {
            var apps = dbContext.Apps
                .Include(x => x.AppDataPermission)
                .ToList();
            return apps;
        }

I tried following [ https://msdn.microsoft.com/en-us/library/dn314429(v=vs.113).aspx][1]

But I get following error

System.ArgumentNullException occurred
  HResult=0x80004003
  Message=Value cannot be null.
Parameter name: source
  Source=EntityFramework
  StackTrace:
   at System.Data.Entity.Utilities.Check.NotNull[T](T value, String parameterName)
   at System.Data.Entity.QueryableExtensions.Include[T,TProperty](IQueryable`1 source, Expression`1 path)

The problem with mocking the database access code is that the you are mocking the part that is the most complicated (linq-to-sql, navigation properties). I recommend, generally speaking, not to expose DAL objects.

Anyway, you haven't shown your mocking code, but I'm assuming that you are mocking public List<Apps> GetApps() .

Here is one method to mock it:

var mockRepo = new Mock<IMyAmazingRepository>(MockBehavior.Strict);

var myMockedApps = new List<App> () {
  new Apps { ID = 1, Name ="One", new List<AppDataPermission> { (...) },
  new Apps { ID = 2, Name ="Two", new List<AppDataPermission> { (...) }
};

mockRepo.Setup(m => m.GetApps(_loggedInUserId)).Returns(myMockedApps);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM