我想介绍一下这个问题的背景。如果你喜欢就跳过。很长一段时间以来,我一直在密切关注stackoverflow和其他地方关于代码测试的争论,因为它与EF有关。一个阵营说,直接针对数据库进行测试,因为Linq-to-Objects&Sql及其实现。另一个则嘲讽地说测试。
另一个意见分歧是使用存储库的问题,或者接受DbContext和DbSet已经提供了工作单元和存储库模式的问题。在我使用EF的这段时间里,我尝试了这些阵营提供的每一种观点组合。不管我做了什么,EF都很难测试。
我很高兴发现EF团队让DbSet在EF 6中更具可模仿性。他们还提供了关于如何模拟DbSet的文档,包括使用Moq的异步方法。在我最近的一个涉及WebApi的项目中,我意识到,如果我能模仿EF,我就可以跳过编写存储库,因为编写存储库的正常原因是让事情变得可测试。灵感来自于阅读了一些博客文章,比如这样。。。
--背景结束---
实际的问题是,按照EF团队给出的关于如何Moq-DbSet的示例代码,如果在任何代码中使用.Include(),就会引发ArgumentNullException。
SO 上的其他相关帖子
这是我的DbContext:接口
public interface ITubingForcesDbContext
{
DbSet<WellEntity> Wells { get; set; }
int SaveChanges();
Task<int> SaveChangesAsync();
Task<int> SaveChangesAsync(CancellationToken cancellationToken);
}
这是我的控制器处理的主要实体
public class WellEntity
{
public int Id { get; set; }
public DateTime DateUpdated { get; set; }
public String UpdatedBy { get; set; }
[Required]
public string Name { get; set; }
public string Location { get; set; }
public virtual Company Company { get; set; }
public virtual ICollection<GeometryItem> GeometryItems
{
get { return _geometryItems ?? (_geometryItems = new Collection<GeometryItem>()); }
protected set { _geometryItems = value; }
}
private ICollection<GeometryItem> _geometryItems;
public virtual ICollection<SurveyPoint> SurveyPoints
{
get { return _surveyPoints ?? (_surveyPoints = new Collection<SurveyPoint>()); }
protected set { _surveyPoints = value; }
}
private ICollection<SurveyPoint> _surveyPoints;
public virtual ICollection<TemperaturePoint> TemperaturePoints
{
get { return _temperaturePoints ?? (_temperaturePoints = new Collection<TemperaturePoint>()); }
protected set { _temperaturePoints = value; }
}
private ICollection<TemperaturePoint> _temperaturePoints;
}
这是直接使用EF DbContext 的控制器
[Route("{id}")]
public async Task<IHttpActionResult> Get(int id)
{
var query = await TheContext.Wells.
Include(x => x.GeometryItems).
Include(x => x.SurveyPoints).
Include(x => x.TemperaturePoints).
SingleOrDefaultAsync(x => x.Id == id);
if (query == null)
{
return NotFound();
}
var model = ModelFactory.Create(query);
return Ok(model);
}
最后是失败的测试。。。
测试设置---
[ClassInitialize]
public static void ClassInitialize(TestContext testContest)
{
var well1 = new WellEntity { Name = "Well 1" };
var well2 = new WellEntity { Name = "Well 2" };
var well3 = new WellEntity { Name = "Well 3" };
var well4 = new WellEntity { Name = "Well 4" };
well1.GeometryItems.Add(new GeometryItem());
well1.TemperaturePoints.Add(new TemperaturePoint());
well1.SurveyPoints.Add(new SurveyPoint());
well2.GeometryItems.Add(new GeometryItem());
well2.TemperaturePoints.Add(new TemperaturePoint());
well2.SurveyPoints.Add(new SurveyPoint());
well3.GeometryItems.Add(new GeometryItem());
well3.TemperaturePoints.Add(new TemperaturePoint());
well3.SurveyPoints.Add(new SurveyPoint());
well4.GeometryItems.Add(new GeometryItem());
well4.TemperaturePoints.Add(new TemperaturePoint());
well4.SurveyPoints.Add(new SurveyPoint());
var wells = new List<WellEntity> { well1, well2, well3, well4 }.AsQueryable();
var mockWells = CreateMockSet(wells);
_mockContext = new Mock<ITubingForcesDbContext>();
_mockContext.Setup(c => c.Wells).Returns(mockWells.Object);
}
private static Mock<DbSet<T>> CreateMockSet<T>(IQueryable<T> data) where T : class
{
var mockSet = new Mock<DbSet<T>>();
mockSet.As<IDbAsyncEnumerable<T>>()
.Setup(m => m.GetAsyncEnumerator())
.Returns(new TestDbAsyncEnumerator<T>(data.GetEnumerator()));
mockSet.As<IQueryable<T>>()
.Setup(m => m.Provider)
.Returns(new TestDbAsyncQueryProvider<T>(data.Provider));
mockSet.As<IQueryable<T>>().Setup(m => m.Expression).Returns(data.Expression);
mockSet.As<IQueryable<T>>().Setup(m =>m.ElementType).Returns(data.ElementType);
mockSet.As<IQueryable<T>>().Setup(m=>m.GetEnumerator()).
Returns(data.GetEnumerator());
return mockSet;
}
[TestMethod]
public async Task Get_ById_ReturnsWellWithAllChildData()
{
// Arrange
var controller = new WellsController(_mockContext.Object);
// Act
var actionResult = await controller.Get(1);
// Assert
var response = actionResult as OkNegotiatedContentResult<WellModel>;
Assert.IsNotNull(response);
Assert.IsNotNull(response.Content.GeometryItems);
Assert.IsNotNull(response.Content.SurveyPoints);
Assert.IsNotNull(response.Content.TemperaturePoints);
}
TestDbAsyncQueryProvider;TestDbAsyncEnumerator直接来自引用的EF团队文档。我已经尝试了几种不同的变体来创建mock的数据,但没有成功。
对于任何对如何使用NSubstitute和Entity Framework 6+解决.Include("Foo")
问题感兴趣的人,我可以通过以下方式绕过我的Include
调用:
var data = new List<Foo>()
{
/* Stub data */
}.AsQueryable();
var mockSet = Substitute.For<DbSet<Foo>, IQueryable<Foo>>();
((IQueryable<Post>)mockSet).Provider.Returns(data.Provider);
((IQueryable<Post>)mockSet).Expression.Returns(data.Expression);
((IQueryable<Post>)mockSet).ElementType.Returns(data.ElementType);
((IQueryable<Post>)mockSet).GetEnumerator().Returns(data.GetEnumerator());
// The following line bypasses the Include call.
mockSet.Include(Arg.Any<string>()).Returns(mockSet);
下面是一个使用Moq的完整示例。您可以将整个示例粘贴到单元测试类中。感谢@jbaum012和@Skuli的评论。我还推荐微软的优秀教程。
// An Address entity
public class Address
{
public int Id { get; set; }
public string Line1 { get; set; }
}
// A Person referencing Address
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public virtual Address Address { get; set; }
}
// A DbContext with persons and devices
// Note use of virtual (see the tutorial reference)
public class PersonContext : DbContext
{
public virtual DbSet<Person> Persons { get; set; }
public virtual DbSet<Address> Addresses { get; set; }
}
// A simple class to test
// The dbcontext is injected into the controller
public class PersonsController
{
private readonly PersonContext _personContext;
public PersonsController(PersonContext personContext)
{
_personContext = personContext;
}
public IEnumerable<Person> GetPersons()
{
return _personContext.Persons.Include("Address").ToList();
}
}
// Test the controller above
[TestMethod]
public void GetPersonsTest()
{
var address = new Address { Id = 1, Line1 = "123 Main St." };
var expectedPersons = new List<Person>
{
new Person { Id = 1, Address = address, Name = "John" },
new Person { Id = 2, Address = address, Name = "John Jr." },
};
var mockPersonSet = GetMockDbSet(expectedPersons.AsQueryable());
mockPersonSet.Setup(m => m.Include("Address")).Returns(mockPersonSet.Object);
var mockPersonContext = new Mock<PersonContext>();
mockPersonContext.Setup(o => o.Persons).Returns(mockPersonSet.Object);
// test the controller GetPersons() method, which leverages Include()
var controller = new PersonsController(mockPersonContext.Object);
var actualPersons = controller.GetPersons();
CollectionAssert.AreEqual(expectedPersons, actualPersons.ToList());
}
// a helper to make dbset queryable
private Mock<DbSet<T>> GetMockDbSet<T>(IQueryable<T> entities) where T : class
{
var mockSet = new Mock<DbSet<T>>();
mockSet.As<IQueryable<T>>().Setup(m => m.Provider).Returns(entities.Provider);
mockSet.As<IQueryable<T>>().Setup(m => m.Expression).Returns(entities.Expression);
mockSet.As<IQueryable<T>>().Setup(m => m.ElementType).Returns(entities.ElementType);
mockSet.As<IQueryable<T>>().Setup(m => m.GetEnumerator()).Returns(entities.GetEnumerator());
return mockSet;
}
在这里玩这个并引用答案对扩展方法调用的设置结果看起来Moq不能模拟静态扩展方法
我试着添加:
mockSet.Setup(t => t.FirstAsync()).Returns(Task.FromResult(data.First()));
mockSet.Setup(t => t.FirstAsync(It.IsAny<Expression<Func<T, bool>>>())).Returns(Task.FromResult(data.First()));
Moq抱怨道:
System.NotSupportedException:表达式引用的方法不属于模拟对象:t=>t.FirstAsync()
看来有三种选择:
- 重构代码以进一步隔离dbcontext,这样就不必测试这种行为
- 从DbSet切换到IDbSet而不是嘲讽DbContext
- 允许您的测试创建SQL紧凑型数据库用数据填充它以便运行测试
我设法用一种通用方法模拟了Moq中的Include。尽管这并没有涵盖Include()的所有用法,只涉及字符串和表达式,但它符合我的需求:
public Mock<DbSet<T>> SetupMockSetFor<T>(Expression<Func<DbContext, DbSet<T>>> selector) where T : class
{
var mock = new Mock<DbSet<T>>();
mock.ResetCalls();
this.EntitiesMock.Setup(m => m.Set<T>()).Returns(mock.Object);
this.EntitiesMock.Setup(selector).Returns(mock.Object);
mock.Setup(x => x.Include(It.IsAny<string>())).Returns(mock.Object);
try
{
mock.Setup(x => x.Include(It.IsAny<Expression<Func<T, object>>>()))
.Returns(mock.Object);
}
catch
{
// Include only applies to some objects, ignore where it doesn't work
}
return mock;
}
测试用途:
var mockCourseSet = SetupMockSetFor(entities => entities.Courses);
在役方式:
var foundCourses = dbContext.Courses.Include(c => c.CourseParticipants).Where(c => c.Id = courseId)
DbSet
就是一个示例。
如果你想模拟Include
(或FindAsync
),你必须自己做。