我正在使用Xunit&起订量我希望能够模拟插入到表中.这样,记录实际上不会填充表,但是单元测试可以验证插入是否成功.使用真实的DbContext,单元测试适用于下面的方法Add_Works().当我尝试在Add_WantToWork()中模拟时,出现错误“对象引用未设置为对象的实例”.该失败发生在ARepository类的Context.Set().Add(entity)上,也如下所示.它由uw.Table1.Add(_table1)调用.
public class UnitTestClass
{
private readonly Table1 _table1 = new Table1()
{
TypeId = 4,
Name = "TestAutomation",
Description = "Test Automation",
CreatedDate = DateTime.Now
};
[Fact]
public void Add_Works()
{
int rowsAffected = 0;
using (var uw = new UnitOfWork(new PortalDbContext()))
{
uw.Table1.Add(_table1);
rowsAffected = uw.Commit();
}
Assert.Equal(1, rowsAffected);
}
[Fact]
public void Add_WantToWork()
{
int rowsAffected = 0;
var mockContext = new Mock<TestDbContext>();
using (var uw = new UnitOfWork(mockContext.Object))
{
uw.Table1.Add(_table1);
rowsAffected = uw.Commit();
}
Assert.Equal(1, rowsAffected);
}
}
public abstract class ARepository<TEntity, TPrimaryKey> : IRepository<TEntity, TPrimaryKey>
where TEntity : class, IEntity<TPrimaryKey>
{
protected readonly DbContext Context;
protected ARepository(DbContext context)
{
Context = context;
}
public void Add(TEntity entity)
{
Context.Set<TEntity>().Add(entity);
}
}
解决方法:
问题是您在嘲笑对象,但没有对象的方法.
就像这样:
mockContext.Setup(p => p.Set<Table1>().Add(It.IsAny<Table1>())).Returns(_table1);
这样,模拟将创建dbSet的实例并返回您想要的任何内容