Partial mocking of class with Moq

China☆狼群 提交于 2019-12-04 17:47:36

问题


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;
    }
}

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.

This is my test:

[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();
 }

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

and then

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

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


回答1:


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.

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



回答2:


Did you try to specify Verifiable:

my.Setup(mock => mock.GetValue()).Callback(() => Console.WriteLine("MOCKED GetValue")).Returns(999).Verifiable();


来源:https://stackoverflow.com/questions/11017967/partial-mocking-of-class-with-moq

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!