Moq调用未在模拟中执行 [英] Moq Invocation was not performed on the mock

查看:90
本文介绍了Moq调用未在模拟中执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图了解verifySet等的用法...但是除非我采取解决方法,否则无法使其正常工作.

Trying to understand the use of verifySet etc... but unless I do a workaround I cannot get it to work.

public interface IProduct
{
    int  Id { get; set; }
    string Name { get; set; }
}


public void Can_do_something()
{
    var newProduct = new Mock<IProduct>();
    newProduct.SetupGet(p => p.Id).Returns(1);
    newProduct.SetupGet(p => p.Name).Returns("Jo");

    //This fails!! why is it because I have not invoked it
    newProduct.VerifySet(p => p.Name, Times.AtLeastOnce());

    //if I do this it works
    newProduct.Object.Name = "Jo";
    newProduct.VerifySet(p => p.Name, Times.AtLeastOnce());
 }

有人可以阐明我应该如何在属性上使用VerifySet以及Verify和VerifyGet吗? 我很困惑.

Can somebody clarify how I should use VerifySet and Verify and VerifyGet on a property? I am getting confused.

推荐答案

在调用verify之前,您需要执行一个操作.具有模拟对象的典型单元测试范例是:

You need to perform an action before you call verify. The typical unit test paradigm with mock objects is:

// Arrange
// Act
// Assert

以下是不正确的用法,因为您缺少操作"步骤:

So the following is improper usage because you're missing your Act step:

public void Can_do_something()
{
    // Arrange
    var newProduct = new Mock<IProduct>();
    newProduct.SetupGet(p => p.Name).Returns("Jo");

    // Act - doesn't exist!
    // Your action against p.Name (ie method call), should occur here

    // Assert
    // This fails because p.Name has not had an action performed against it
    newProduct.VerifySet(p => p.Name, Times.AtLeastOnce());
}

这是正确的,因为存在法案:

And this is correct, since Act exists:

public void Can_do_something()
{
    // Arrange
    var newProduct = new Mock<IProduct>();
    newProduct.SetupGet(p => p.Name).Returns("Jo");

    // Act
    LoadProduct(newProduct.Object);

    // Assert
    newProduct.VerifySet(p => p.Name, Times.AtLeastOnce());
}

public static void LoadProduct(IProduct product)
{
    product.Name = "Jo";
}

模拟测试所遵循的模式不同于称为行为验证的非模拟测试-这是

Mock testing follows a different pattern than Non-Mock testing known as Behavior Verification - this is an answer I made that will clarify the concept a bit more.

这篇关于Moq调用未在模拟中执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆