I'm trying to follow this guide for mocking Entity Framework
https://msdn.microsoft.com/en-us/library/dn314429.aspx
The code from the guide works absolutely fine when I build it in my project, but when I'm trying to apply it to my actual context and data objects, I'm getting an exception:
Object reference not set to an instance of an object
My object is pretty simple:
public class NodeAttributeTitle
{
public int ID { get; set; }
[MaxLength(150)]
public string Title { get; set; }
public string Description { get; set; }
}
as is my context
public class DataContext : DbContext
{
public virtual DbSet<NodeAttributeTitle> NodeAttributeTitles { get; set; }
}
and the method I'm trying to set is just a basic insertion
public class CommonNodeAttributes : ICommonNodeAttributes
{
private DataContext _context;
public CommonNodeAttributes(DataContext context)
{
_context = context;
}
public CommonNodeAttributes()
{
_context = new DataContext();
}
public void Insert(string value)
{
var nodeAttributeValue = new NodeAttributeValue();
nodeAttributeValue.Value = value;
nodeAttributeValue.Parent = 0;
_context.NodeAttributeValues.Add(nodeAttributeValue);
_context.SaveChanges();
}
}
And the test class is following the same syntax as in the MSDN guide
[TestClass]
public class CommonNodeAttributesTests
{
[TestMethod]
public void CreateNodeAttribute_saves_a_nodeattribute_via_context()
{
var mockSet = new Mock<DbSet<NodeAttributeTitle>>();
var mockContext = new Mock<DataContext>();
mockContext.Setup(m => m.NodeAttributeTitles).Returns(mockSet.Object);
var service = new CommonNodeAttributes(mockContext.Object);
service.Insert("blarg");
mockSet.Verify(m => m.Add(It.IsAny<NodeAttributeTitle>()),Times.Once());
mockContext.Verify(m => m.SaveChanges(),Times.Once);
}
}
and yet when the test runs, I get
Tests.CommonNodeAttributesTests.CreateNodeAttribute_saves_a_nodeattribute_via_context threw exception:
System.NullReferenceException: Object reference not set to an instance of an object.
I don't understand why the code in the guide works fine, but my code doesn't.
I've tried adding 'virtual' to the ID, Title and Description properties but that doesn't do anything either. Does anyone have any clue what might be different for me?