本文介绍了类偏嘲讽与起订量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想嘲笑下面的类仅的GetValue 的方法,用起订量:

I want to mock only the GetValue method of the following class, using Moq:

public class MyClass
{
    public virtual void MyMethod()
    {
        int value = GetValue();
        Console.WriteLine("ORIGINAL MyMethod: " + value);
    }

    internal virtual int GetValue()
    {
        Console.WriteLine("ORIGINAL GetValue");
        return 10;
    }
}

我已经读了一下,这应该如何搭配起订量。我在网上找到的解决方案是使用 CallBase 属性,但是,这并不为我工作。

I already read a bit how this should work with Moq. The solution that I found online is to use the CallBase property, but that doesn't work for me.

这是我的测试:

[Test]
public void TestMyClass()
{
     var my = new Mock<MyClass> { CallBase = true };
     my.Setup(mock => mock.GetValue()).Callback(() => Console.WriteLine("MOCKED GetValue")).Returns(999);
     my.Object.MyMethod();
     my.VerifyAll();
 }

我希望这起订量使用的MyMethod 的现有实现并调用嘲笑的方法,导致下面的输出:

I would expect that Moq uses the existing implementation of MyMethod and calls the mocked method, resulting in the following output:

ORIGINAL MyMethod: 999
MOCKED GetValue

但是这就是我得到的:

but that's what I get :

ORIGINAL GetValue
ORIGINAL MyMethod: 10

然后

Moq.MockVerificationException : The following setups were not matched: MyClass mock => mock.GetValue()

我的感觉,我完全误解的东西。我在想什么吗?任何帮助将是AP preciated

I got the feeling, that I misunderstood something completely. What am I missing here?Any help would be appreciated

推荐答案

OK,我发现另一个问题的答案是:的。因此,这是一个重复的,并且可以被关闭。

OK, I found the answer to this in another question: How to Mock the Internal Method of a class?. So this is a duplicate and can be closed.

不过,这里的解决方案:要测试这一行只是添加到 Assembly.config 项目:

Nevertheless, here's the solution:just add this line to the Assembly.config of the project you want to test:

[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] // namespace in Moq

这篇关于类偏嘲讽与起订量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 00:20