Mocking virtual members in Moq

c#, moq

Solution

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

Problem

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

Original source