验证方法被调用

Verifying a method was called(验证方法被调用)
本文介绍了验证方法被调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

使用起订量时,我遇到了一个非常奇怪的问题,即只有当我设置的方法是公开的时,模拟上的设置似乎才有效.我不知道这是 Moq 错误还是我只是有这个错误(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);     
}

失败并显示此消息:

Say_WhenPublic_CallsHello 失败:Moq.MockException:未在模拟上执行 1 次调用:x => x.Hello()在 Moq.Mock.ThrowVerifyException(预期 IProxyCall,表达式表达式,Times 次)...

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)...

如果我像这样公开 Hello 方法,则测试通过.这里有什么问题?

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

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

提前致谢!

推荐答案

Hello() 是 internal 时测试失败,因为在这种情况下 Moq 无法提供方法的覆盖.这意味着 Hello() 的内部实现将运行,而不是 mock 的版本,导致 Verify() 失败.

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.

顺便说一句,您在这里所做的事情在单元测试的上下文中毫无意义.单元测试不应该关心 Say() 调用内部 Hello() 方法.这是程序集内部的实现,与使用代码无关.

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.

这篇关于验证方法被调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to MOQ an Indexed property(如何最小起订量索引属性)
Mocking generic methods in Moq without specifying T(在 Moq 中模拟泛型方法而不指定 T)
How Moles Isolation framework is implemented?(Moles Isolation 框架是如何实现的?)
Difference between Dependency Injection and Mocking Framework (Ninject vs RhinoMocks or Moq)(依赖注入和模拟框架之间的区别(Ninject vs RhinoMocks 或 Moq))
How to mock Controller.User using moq(如何使用 moq 模拟 Controller.User)
How do I mock a class without an interface?(如何模拟没有接口的类?)