Manny
Manny

Reputation: 833

Mocking virtual members in 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

Upvotes: 17

Views: 10644

Answers (2)

Sathish
Sathish

Reputation: 2099

 var systemUnderTest = new Moq.Mock<ProcessBulkData> { CallBase = true };
 systemUnderTest.Setup(s => s.MethodName(...)).Returns(...);
 var actual=systemUnderTest.Object.BulkInsert(...);

Upvotes: 2

Matt Enright
Matt Enright

Reputation: 7484

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

Upvotes: 26

Related Questions