12

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

Fabian
  • 781
  • 2
  • 8
  • 17
  • possible duplicate of [When mocking a class with Moq, how can I CallBase for just specific methods?](http://stackoverflow.com/questions/2822947/when-mocking-a-class-with-moq-how-can-i-callbase-for-just-specific-methods) – StriplingWarrior Jun 13 '12 at 15:14
  • If you make your `GetValue` method `public` instead of `internal` it works. I don't know why maybe this is a limitation of castle dynamic proxy, or is it a bug a Moq, or this is the intended behavior. Anyway if you leave it as internal you cannot put your production code to a different assembly unless you use InternalVisibleTo. – nemesv Jun 13 '12 at 15:27
  • possible duplicate of [Verifying a method was called](http://stackoverflow.com/questions/1980108/verifying-a-method-was-called) – nemesv Jun 13 '12 at 15:30
  • well, it really does work if I change `GetValue`to `public`. That's a real bummer. I've got a very complex class that uses a private method to write its result to an ascii-file. I only wanted to get rid of that file and check the string directly in my unit test. How am I supposed to do this? – Fabian Jun 13 '12 at 15:52

2 Answers2

8

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
Community
  • 1
  • 1
Fabian
  • 781
  • 2
  • 8
  • 17
0

Did you try to specify Verifiable:

my.Setup(mock => mock.GetValue()).Callback(() => Console.WriteLine("MOCKED GetValue")).Returns(999).Verifiable();
Felice Pollano
  • 32,832
  • 9
  • 75
  • 115