Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking virtual members in Moq

Tags:

c#

moq

For unit testing, I'm using NUnit 2.6 and Moq 4.0. There's a particular case concerning virtual members where Moq's proxy objects don't relay method calls to the actual implementation (probably by design). For instance, if I had a class...

public class MyClass {
    protected virtual void A() {
        /* ... */
    }

    protected virtual void B(...) {
        /* ... */
    }
}

...and I use Moq to override GetSomethingElse's A() method in my test fixture...

var mock = new Mock<MyClass>();
mock.Protected().Setup("A").Callback(SomeSortOfCallback);

...using the mock's A method works splendidly; however, if anything in said method would call not-mocked method B, the method will do nothing and/or return default values, even if an actual implementation exists in MyClass.

Is there a way to work around this? Am I using Moq wrong?

Thanks in advance,
Manny

like image 297
Manny Avatar asked Jul 09 '12 08:07

Manny


People also ask

How do you mock a method in MOQ?

First, we instantiate the FakeDbArticleMock class and indicate which setup we want to use for this test. Then, it is necessary to instantiate the repository we want to test and inject the mock instance into it. Finally, we call the method we are testing and assert the results.

What is CallBase in MOQ?

CallBase , when initialized during a mock construction, is used to specify whether the base class virtual implementation will be invoked for mocked dependencies if no setup is matched. The default value is false . This is useful when mocking HTML/web controls of the System.


2 Answers

Set mock.CallBase = true and you should be good to go.

like image 153
Matt Enright Avatar answered Oct 20 '22 12:10

Matt Enright


 var systemUnderTest = new Moq.Mock<ProcessBulkData> { CallBase = true };
 systemUnderTest.Setup(s => s.MethodName(...)).Returns(...);
 var actual=systemUnderTest.Object.BulkInsert(...);
like image 32
Sathish Avatar answered Oct 20 '22 13:10

Sathish