我对 Moq 框架和单元很陌生。我的目标是向模拟对象插入一些信息,并希望能够计算插入当前值的对象数量。
我通过以下方式构建我的模拟:
var mockCpmSqlDbContext = new Mock<CpmSqlDbContext>();
var mockSetPolicies = new Mock<DbSet<Policies>>();
var dataStore = new List<Policies>
{
new Policies
{
PolicyID = 1,
PolicyName = "policy1",
PolicyDesc = "policy1desc"
},
new Policies
{
PolicyID = 2,
PolicyName = "policy2",
PolicyDesc = "policy2desc"
},
};
var policyData = dataStore.AsQueryable();
mockSetPolicies.As<IQueryable<Policies>>().
Setup(m => m.Provider).Returns(policyData.Provider);
mockSetPolicies.As<IQueryable<Policies>>().
Setup(m => m.Expression).Returns(policyData.Expression);
mockSetPolicies.As<IQueryable<Policies>>().
Setup(m => m.ElementType).Returns(policyData.ElementType);
mockSetPolicies.As<IQueryable<Policies>>().
Setup(m => m.GetEnumerator()).Returns(policyData.GetEnumerator());
mockSetPolicies.Setup(x => x.Create<Policies>()).Returns(() => new Policies());
mockSetPolicies.Setup(x => x.Add(It.IsAny<Policies>())).Callback<Policies>(dataStore.Add);
mockSetPolicies.As<IQueryable<Policies>>().Setup(m => m.GetEnumerator()).Returns(() => policyData.GetEnumerator());
mockSetPolicies.Setup(x => x.Find(It.IsAny<Policies>()));
mockCpmSqlDbContext.Setup(m => m.Policies).Returns(mockSetPolicies.Object);
var service = new MSsqlProvider(mockCpmSqlDbContext.Object);
我目前在我的模拟上下文中有两个策略。我想再添加两个具有相同名称“policy2”的策略,因此添加后我将拥有三个策略名称为“policy2”的对象。
service.AddPolicy(new Policies {PolicyID = 3, PolicyName = "policy2", PolicyDesc = "pDesc3"});
service.AddPolicy(new Policies { PolicyID = 4, PolicyName = "policy2", PolicyDesc = "pDesc3" });
我的添加策略功能:
public void AddPolicy(Policies policy)
{
_dbEntities.Policies.Add(policy);
_dbEntities.SaveChanges();
}
检查断言的代码:
//Assert
var expected = 3;
//first, can I know how many object I have the policy name "policy2".
var actual = mockSetPolicies.Object.Count(p => p.PolicyName == "policy2");
//second, can I assert the number of objects I have currently with the name "policy2".
Assert.AreEqual(expected, actual);
这段代码现在可以正常工作