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
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.
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.
Set mock.CallBase = true
and you should be good to go.
var systemUnderTest = new Moq.Mock<ProcessBulkData> { CallBase = true };
systemUnderTest.Setup(s => s.MethodName(...)).Returns(...);
var actual=systemUnderTest.Object.BulkInsert(...);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With