我想测试一个方法在特定条件下向DBSet添加记录:
public static void AddTriggeredInternalTransactions(IDataContext dc,ExternalTransaction transaction) { if (transaction [meets condition A]) dc.InternalTransactions.CreateInverseTransaction(transaction); // do other stuff under other conditions } private static void CreateInverseTransaction(this IDbSet<InternalTransaction> transactions,ExternalTransaction from) { var internalTransaction = transactions.Create(); from.copyToInternalTransaction(internalTransaction); transactions.Add(internalTransaction); }
现在,我已经有了copyToInternalTransaction()的测试.我只需要调用AddTriggeredInternalTransactions()并验证[条件A]是否会导致添加新记录.
我从http://msdn.microsoft.com/en-us/data/dn314429.aspx开始,然后使用其他Google和StackOverflow搜索.在处理我的“真实”测试之前,我正在尝试进行一项简单的测试,以验证是否已将记录添加到数据集中,但我仍然坚持这一点.任何人都可以指出我的缺陷吗?
var internals = new Mock<DbSet<InternalTransaction>>(); var theData = new List<InternalTransaction>().AsQueryable(); internals.As<IQueryable<InternalTransaction>>().Setup(m => m.Provider).Returns(theData.Provider); internals.As<IQueryable<InternalTransaction>>().Setup(m => m.Expression).Returns(theData.Expression); internals.As<IQueryable<InternalTransaction>>().Setup(m => m.ElementType).Returns(theData.ElementType); internals.As<IQueryable<InternalTransaction>>().Setup(m => m.GetEnumerator()).Returns(theData.GetEnumerator()); var mockDC = new Mock<IDataContext>(); mockDC.Setup(q => q.InternalTransactions).Returns(internals.Object); mockDC.Setup(q => q.InternalTransactions.Create()).Returns(new InternalTransaction()); mockDC.Setup(q => q.InternalTransactions.Add(It.IsAny<InternalTransaction>())); var it = mockDC.Object.InternalTransactions.Create(); it.Id = "123"; mockDC.Object.InternalTransactions.Add(it); internals.Verify(e => e.Add(It.Is<InternalTransaction>(d => d.Id == "123")),Times.Once()); //or: Assert.Equal(1,mockDC.Object.InternalTransactions.Count());
此测试失败:在模拟上预期调用一次,但是为0次:e => e.Add(It.Is(d => d.Id ==“123”))未配置任何设置.没有进行任何调用.
如果使用Assert语句,则会失败并显示NotImplementedException:“成员IQueryable.Provider尚未在DbSet1继承自DbSet1的类型DbSet~1Proxy_1上实现.DbSet1的测试双精度必须提供所使用的方法和属性的实现.”
解决方法
在Adam和Stuart的评论以及进一步的实验之后,我能够将我的测试用例减少到以下工作测试用例:
var internals = new Mock<DbSet<InternalTransaction>>(); var mockDC = new Mock<IDataContext>(); mockDC.Setup(q => q.InternalTransactions).Returns(internals.Object); internals.Setup(q => q.Create()).Returns(new InternalTransaction()); var transaction = new ExternalTransaction { [set criteria for Condition A] }; SomeBusinessObject.AddTriggeredInternalTransactions(mockDC.Object,transaction); // verify the Add method was executed exactly once internals.Verify(e => e.Add(It.IsAny<InternalTransaction>()),Times.Once());
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。