![](/img/trans.png)
[英]HtmlGenericControl gives me an error “Object reference not set to an instance of an object”
[英]Mocking Entity Framework gives me Object reference not set to an instance of an object
我正在嘗試按照本指南來模擬實體框架
https://msdn.microsoft.com/en-us/library/dn314429.aspx
當我在我的項目中構建它時,指南中的代碼工作得非常好,但是當我嘗試將它應用到我的實際上下文和數據對象時,我得到一個例外:
你調用的對象是空的
我的目標非常簡單:
public class NodeAttributeTitle
{
public int ID { get; set; }
[MaxLength(150)]
public string Title { get; set; }
public string Description { get; set; }
}
就我的情況而言
public class DataContext : DbContext
{
public virtual DbSet<NodeAttributeTitle> NodeAttributeTitles { get; set; }
}
我試圖設置的方法只是一個基本的插入
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();
}
}
測試類遵循與MSDN指南中相同的語法
[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);
}
}
然而,當測試運行時,我明白了
Tests.CommonNodeAttributesTests.CreateNodeAttribute_saves_a_nodeattribute_via_context拋出異常:
System.NullReferenceException:未將對象引用設置為對象的實例。
我不明白為什么指南中的代碼工作正常,但我的代碼沒有。
我已經嘗試將“虛擬”添加到ID,標題和描述屬性,但這也沒有做任何事情。 有沒有人知道對我來說可能有什么不同?
您需要在模擬中提供一些數據:
IQueryable<NodeAttributeTitle> data = new List<NodeAttributeTitle>
{
new NodeAttributeTitle() {Id = 1, Title = "t1"},
new NodeAttributeTitle() {Id = 2, Title = "t2"},
}.AsQueryable();
var mockSet = new Mock<IDbSet<NodeAttributeTitle>>();
mockSet .Setup(m => m.Provider).Returns(data.Provider);
mockSet .Setup(m => m.Expression).Returns(data.Expression);
mockSet .Setup(m => m.ElementType).Returns(data.ElementType);
mockSet .Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator());
然后你可以將它傳遞給你的DbContext:
您在代碼中的問題是在Add方法中( _context.NodeAttributeValues.Add(nodeAttributeValue); )沒有被模擬 !
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.