[英]Partial mocking of class with Moq
I want to mock only the GetValue
method of the following class, using Moq: 我想使用Moq仅模拟以下类的
GetValue
方法:
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. 我已经阅读了一下这应该如何与Moq一起使用。 The solution that I found online is to use the
CallBase
property, but that doesn't work for me. 我在网上找到的解决方案是使用
CallBase
属性,但这对我不起作用。
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: 我希望Moq使用
MyMethod
的现有实现并调用mocked方法,从而产生以下输出:
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
任何帮助,将不胜感激
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.config
:
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] // namespace in Moq
您是否尝试指定可验证的:
my.Setup(mock => mock.GetValue()).Callback(() => Console.WriteLine("MOCKED GetValue")).Returns(999).Verifiable();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.