UnitTesing with Autofac, Moq - Getting Value cannot be null exception

1

I'm using EF6. The generated code is something like:

public partial class MyDataContext : DbContext,IMyDataContext 
{
    public MyDataContext() : base("name=mydata")
    {
    }

    public virtual DbSet<getProjectsDraft> getProjectsDrafts { get; set; }
}

and the dbcontext interface is like this:

public interface IMediciDbContext : IDisposable
{
     DbSet<getProjectsDraft> getProjectsDrafts { get; set; }
}

I am using the Autofac for the DI and the registration is done at my global.asax.cs as below

// Entity Registering
builder.RegisterType<MyDataContext>().As<IMyDataContext>();

All my DI is working fine but when I implemented unit testing using xUnity I am getting an error (shown below).

Basetest Code:

public class BaseTest
{
    public static Mock<DbSet<T>> CreateDbSetMock<T>(IEnumerable<T> elements) where T : class
    {
        var elementsAsQueryable = elements.AsQueryable();
        var dbSetMock = new Mock<DbSet<T>>();
        dbSetMock.As<IQueryable<T>>().Setup(m => m.Provider).Returns(elementsAsQueryable.Provider);
        dbSetMock.As<IQueryable<T>>().Setup(m => m.Expression).Returns(elementsAsQueryable.Expression);
        dbSetMock.As<IQueryable<T>>().Setup(m => m.ElementType).Returns(elementsAsQueryable.ElementType);
        dbSetMock.As<IQueryable<T>>().Setup(m => m.GetEnumerator()).Returns(elementsAsQueryable.GetEnumerator());

        return dbSetMock;
    }
}

and Project Test

public class Projects_Test : BaseTest
{
        [Fact]
        public void GetDraftProjectsList()
        {
            // Arrange
            var fixture = new Fixture();
            var draftProjects = new List<getProjectsDraft>
             {
                fixture.Create<getProjectsDraft>()
             };
            var draftMock = CreateDbSetMock(draftProjects);
            var myDataContextMock= new Mock<IMyDataContext>();
            myDataContextMock.Setup(x => x.getProjectsDrafts).Returns(draftMock.Object);
            var projectService = new ProjectRepo(mediciContextMock.Object);

            // Act
            var draftproject = projectService.GetDraftProjects(true, "test-02", "Test");

            // Assert
            Assert.NotNull(draftproject);
        }
}

However, I get an error

"Value cannot be null.\r\nParameter name: source"

in the //Act section of draftproject.

What am I doing wrong?

Stack Trace Error

System.ArgumentNullException
  HResult=0x80004003
  Message=Value cannot be null.
Parameter name: source
  Source=System.Core
  StackTrace:
   at System.Linq.Queryable.OrderByDescending[TSource,TKey](IQueryable`1 source, Expression`1 keySelector)
   at BusinessLayer.ProjectRepo.GetDraftProjects(Boolean IsOwner, String LoginName, String cbName) in F:\Workspace\BusinessLayer\ProjectUploadRepo.cs:line 473
   at UntiTesting.RepoTesting.Projects_Test.GetDraftProjectsList() in F:\Workspace\UntiTesting\RepoTesting\Projects_Test.cs:line 38

and linq query where I'm getting an error

lstDraftProj = (from proj in mydbEntities.getProjectsDrafts.AsNoTracking()
                orderby proj.ProjectID descending
                select proj).ToList();

"getProjectsDraft.cs" it's dbContext class generated by EF6

namespace XyzProz.DataAccess
{
    using System;
    using System.Collections.Generic;

    public partial class getProjectsDraft
    {
        public int ProjectID { get; set; }
        public string OrderNo { get; set; }
        public string CNumber { get; set; }
        public string Region { get; set; }
        public string Department { get; set; }
        public string Location { get; set; }
        public Nullable<byte> StatusID { get; set; }
        public string Status { get; set; }
        public Nullable<System.DateTime> Modified { get; set; }
    }
}
c#
entity-framework
unit-testing
moq
autofac
asked on Stack Overflow Mar 16, 2020 by Satti • edited Mar 17, 2020 by Satti

1 Answer

1

You are almost there, the DbSet is mocked properly but looking at the method, you will notice the AsNoTracing method which is actually not mocked and it returns null.

lstDraftProj = (from proj in mydbEntities.getProjectsDrafts.AsNoTracking()
                orderby proj.ProjectID descending
                select proj).ToList();

That is also suggested by stack trace:

System.ArgumentNullException HResult=0x80004003 Message=Value cannot be null. Parameter name: source

Since you are already mocking DbSet try mocking the AsNoTracing method as well, e.g:

draftMock.Setup(x => x.AsNoTracking()).Returns(draftMock.Object)
answered on Stack Overflow Mar 17, 2020 by Johnny

User contributions licensed under CC BY-SA 3.0