我正在设置模拟时,奇怪的“模拟上的预期调用至少一次,但从未执行过”错误

时间:2011-10-26 16:19:20

标签: vb.net asp.net-mvc-2 nunit moq

我通过NUnit从Moq收到此错误,但对我来说这并没有太大意义。

“模拟上的预期调用至少一次,但从未执行过:x => x.DeleteItem(。$ VB $ Local_item)”

“at Moq.Mock.ThrowVerifyException(MethodCall expected,IEnumerable 1 setups, IEnumerable 1 actualCalls,Expression expression,Times times,Int32 callCount) 在Moq.Mock.VerifyCalls(Interceptor targetInterceptor,MethodCall expected,Expression expression,Times times) 在Moq.Mock.Verify [T](模拟模拟,表达式1 expression, Times times, String failMessage) at Moq.Mock 1.验证(表达式`1表达式) 在C:\ Projects \ MyProject \ MyProject.UnitTests \ Tests \ ItemBrowsing.vb中的PeekABookEditor.UnitTests.ItemBrowsing.Can_Delete_Item():第167行“

非常相似的代码在C#中运行良好,因此我的错误可能是次要的和语法错误。

这是我的代码:

    <Test()> _
Public Sub Can_Delete_Item()
    'Arrange: Given a repository containing some item...
    Dim mockRepository = New Mock(Of IItemsRepository)()
    Dim item As New Item With {.ItemID = "24", .Title = "i24"}

    mockRepository.Setup(Function(x) x.Items).Returns(New Item() {item}.AsQueryable())

    'Act ... when the user tries to delete that product
    Dim controller = New ItemsController(mockRepository.Object)
    Dim result = controller.Delete(24)

    'Assert ... then it's deleted, and the user sees a confirmation
    mockRepository.Verify(Sub(x) x.DeleteItem(item))
    result.ShouldBeRedirectionTo(New With {Key .action = "List"})
    Assert.AreEqual(DirectCast(controller.TempData("message"), String), "i24 was deleted")

End Sub

有罪行似乎是“mockRepository.Verify(Sub(x)x.DeleteItem(item))”

有关如何解决这个问题的想法吗?

使用C#代码并不完全相同,但这里是:

[Test] 
public void Can_Delete_Product() 
{ 
// Arrange: Given a repository containing some product... 
var mockRepository = new Mock<IProductsRepository>(); 
var product = new Product { ProductID = 24, Name = "P24"}; 
mockRepository.Setup(x => x.Products).Returns( 
    new[] { product }.AsQueryable() 
); 

// Act: ... when the user tries to delete that product 
var controller = new AdminController(mockRepository.Object); 
var result = controller.Delete(24); 

// Assert: ... then it's deleted, and the user sees a confirmation
mockRepository.Verify(x => x.DeleteProduct(product)); 
result.ShouldBeRedirectionTo(new { action = "Index" }); 
controller.TempData["message"].ShouldEqual("P24 was deleted"); 

}

1 个答案:

答案 0 :(得分:0)

在VB测试方法中,您使用字符串Item创建ItemID = "24",但是使用整数值controller.Delete调用24方法。

检查您的控制器代码,看看类型差异是否会导致项目无法正确识别,因此根本不会调用DeleteItem,或者使用不同的Item调用