在我看来,不是通过存储库模式消除对 EF 的依赖,而是在尝试模拟 EF 的特定行为。我看不出尝试这样做有什么意义,这将非常困难,EF 并不是要被嘲笑的。
您的存储库大概是这样的:
public interface IRepository
{
IEnumerable<EmployeeProfiles> EmployeeProfiles { get; }
}
public class Repository
{
public IEnumerable<EmployeeProfiles> EmployeeProfiles
{
get
{
// Get all the entities including children
using (MyContext context = new MyContext())
{
return context.EmployeeProfiles.Include("EmployeeProperties").ToList();
}
}
}
}
这样,您就删除了关于如何返回 EmployeeProfiles 的存储库依赖项。现在您可以随心所欲地模拟(尚未使用 Moles),但使用 Moq,您可以执行以下操作:
public void TestEmptyList()
{
var mock = new Mock<IRepository>();
var expected = new List<EmployeeProfiles>();
mock.SetupGet(ep => ep.EmployeeProfiles).Returns(expected);
var actual = mock.Object.EmployeeProfiles;
Assert.AreEqual(expected, actual);
}
因此,如果您将要从数据库中抽象出来的方法/属性放入存储库接口中,那么您可以模拟出您想要测试它可能返回的任何值。
也许你正在这样做,我不确定。我不明白您为什么要对 EF 进行单元测试,您希望获得什么?这将非常困难,它不是为模拟而设计的(很少有接口/虚拟)。您返回的任何数据模拟,这实际上是您真正感兴趣的所有内容,都将按照上述方式完成。