C# mocked property has value in Debugger but causes null reference

Viewed 19

Why might this be the case?:

  • hovering over the container class (DbContext) shows that the Persons property has a value (Castle.Proxies.) and the Results View shows a List with an item in (as expected).
  • hovering over the property when referenced shows NULL and referencing property causes NullReferenceException

The Container Class is BrokerContext

public interface IBrokerContext : IDisposable
        {
            DbSet<Agents> Agents { get; set; }
            
            IDbContextTransactionProxy BeginTransaction();
        }

        public class BrokerContext : ApplicationDbContext, IBrokerContext
        {
            public new DbSet<Agents> Agents { get; set; }
      ...
     }

The purpose of BrokerContext is to be a proxy/adapter for the ApplicationDbContext so that I can mock BeginTransaction().

My code uses a _db of type ApplicationDbContext which has the Sets declared in BrokerContext. In my test, I am trying to construct a mock of type BrokerContext and pass that object into the class being tested to override the ApplicationDbContext. That way I can control what happens when BeginTransaction() is called.

However, despite doing this:

mockDb.Object.Agents = mockAgentSet.Object;

And passing that mock object into my class being tested, and seeing the property _db.Agents has a value in the debug view: any reference to await _db.Agents returns null!

The DbContext being overriden:

    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
        {
            public virtual DbSet<Agents> Agents { get; set; }
...
}
    
        
0 Answers
Related