[英]How to use Moq with Entity Framework Include()
I am trying write unit test for my DAL layer. 我正在尝试为我的DAL层编写单元测试。
The complication is that the DAL Layer has a query which uses Include(). 复杂之处在于DAL层具有使用Include()的查询。
I don't know how to mock the Include() method. 我不知道如何模拟Include()方法。
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 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] 我尝试了以下[ 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). 模拟数据库访问代码的问题在于,您正在模拟最复杂的部分(linq-to-sql,导航属性)。 I recommend, generally speaking, not to expose DAL objects.
一般来说,我建议不要公开DAL对象。
Anyway, you haven't shown your mocking code, but I'm assuming that you are mocking public List<Apps> GetApps()
. 无论如何,您没有显示您的模拟代码,但我假设您正在
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.