Reputation: 811
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
Upvotes: 12
Views: 14582
Reputation: 811
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
Upvotes: 8
Reputation: 33252
Did you try to specify Verifiable:
my.Setup(mock => mock.GetValue()).Callback(() => Console.WriteLine("MOCKED GetValue")).Returns(999).Verifiable();
Upvotes: 0