我對Moq Framework和unitests很陌生。我的目標是向模擬對象插入一些信息,並且希望能夠用當前值計算插入的對象的數量。使用計數法
我建立我的模擬中的以下方式:
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);
這份代碼現在工作currectly
請問您能否提供更多關於方法'AddPolicy'的信息。什麼是實現?也許你可以驗證對'AddPolicy'的調用,但只有當方法是_virtual_。或者你添加一個新的_interface_到'MSsqlProvider'和'AddPolicy' –
@Dominik Herold添加策略被添加 –