验证的方法被称为被称为、方法

2023-09-02 01:54:51 作者:国服直男第一人!

使用起订量,我有一个很奇怪的问题,即在一个模拟的设置似乎只能工作,如果方法,我设置是公开的。我不知道这是否是一个起订量错误,或者如果我只是有这个毛病(新手MOQ)。下面是测试用例:

Using Moq, I have a very odd issue where the setup on a mock only seems to work if the method I am setting up is public. I don't know if this is a Moq bug or if I just have this wrong (newbie to Moq). Here is the test case:

public class TestClass
{
    public string Say()
    {
        return Hello();
    }

    internal virtual string Hello()
    {
        return "";
    }
}

[TestMethod]
public void Say_WhenPublic_CallsHello()
{
    Mock<TestClass> mock = new Mock<TestClass>();
    mock.Setup(x => x.Hello()).Returns("Hello World");

    string result = mock.Object.Say();
    mock.Verify(x => x.Hello(), Times.Exactly(1));
    Assert.AreEqual("Hello World", result);     
}

这将失败,此消息:

Which fails with this message:

Say_WhenPublic_CallsHello失败:Moq.MockException:   是不是在模仿1次进行调用:X => x.Hello()   在Moq.Mock.ThrowVerifyException(IProxyCall预期,防爆pression EX pression,倍)...

Say_WhenPublic_CallsHello failed: Moq.MockException: Invocation was not performed on the mock 1 times: x => x.Hello() at Moq.Mock.ThrowVerifyException(IProxyCall expected, Expression expression, Times times)...

如果我让你好方法public这样,测试通过。什么是这里的问题?

If I make the Hello method public like this, the test passes. What is the issue here?

public virtual string Hello()
{
    return "";
}

在此先感谢!

Thanks in advance!

推荐答案

在测试失败时您好()是内部的,因为起订量不能提供方法的重写本外壳。这意味着,在内部实现您好()运行,而不是模仿的版本,引起了验证()来失败。

The test fails when Hello() is internal because Moq cannot provide an override of the method in this case. This means that the internal implementation of Hello() will run, rather than mock's version, causing the Verify() to fail.

顺便说一句,你在这里做什么使得在单元测试的情况下毫无意义。单元测试不应该关心说()调用内部您好()方法。这是实施内部程序集和消费code的不是一个问题。

Incidentally, what you are doing here makes no sense in the context of a unit test. A unit test should not care that Say() calls an internal Hello() method. This is implementation internal to your assembly and not a concern of consuming code.