Unit Testing Z Entity Framework Plus Extensions


Question

When using Z.EntityFramework.Plus extensions, I cannot find a way to mock/substitute what the context returns when any of the plus extensions, not just Future(), are being used. Everything I try throws a NullReferenceException within the z extensions future library.

Repository Example:

public Task<DocumentDomain> GetDocuments(int id)
{
  var futureQuery1 = _context.ReportTypes.Where(x => x.IsReadOnly).Future();
  var futureQuery2 = _context.Reports.Where(x => x.CreateDate < DateTime.Now.AddDays(-10)).Future();
  var futureQuery3 = _context.Person.DeferredFirstOrDefault(x => x.Id == id).FutureValue();

   return new DocumentDomain(futureQuery1.ToList(), futureQuery2.ToList(), futureQuery3.Value);
}

Unit Test Repository:

    [Fact]
    public async Task ShouldGetDocumentsForPerson1()
    {
       _context = Substitute.For<IMyDbContext>();
       _context.ReportTypes = new FakeDbSet();
       _context.ReportTypes.AddRange(GetFakeReportTypes());
       // ...etc..arrange for Reports and Person

       var repo = new DocumentRepository(_context);

       // CRASHES HERE ON futureQuery1 at .Future()
       var domain = await repo.GetDocuments(1); // fake id

       Assert.IsTrue(domain.Documents.Count > 0);
    }

Without using Futures it works fine. I've tried mocking out a few different ways but always get an error. Most of the time it's a "oops Z extensions encountered an error" exception.

I'm thinking it's because Z extensions is expecting a real ObjectContext but not sure how to overcome this. Has anyone experienced similar issues? Does anyone know of any solutions? Thanks.

Expert Answer

The Future feature is expecting a real ObjectContext. I believe the current scenario fail when the method GetDbContext is called since no context can be found.

I'm not aware of a workaround but it may possible to add an option such UseMockContext that will resolve all queries without batching them (Exactly as if you was not using the Future feature).

Let me know if adding this option it's something that could solve your current problem.

If this is the case, I suggest you creating an issue here: https://github.com/zzzprojects/EntityFramework-Plus/issues





Licensed under: CC-BY-SA
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why