1

I'm looking to test a method that uses code from a third party dependency. This dependency defines and interface - IPublishedContent - that is passed a parameter to the method I want to test.

Within my method I'm calling a method on IPublishedContent called GetPropertyValue. However this method isn't defined directly on the interface, it's added in by an extension method also provided by the third party dependency.

Given that, I can't use Moq as I normally would to mock the extension method.

Instead I figured I would create a stub class that implements IPublishedContent, and pass an instance of that as the parameter in my test. I added the method I want to test as an instance method on my stub.

Now, my understanding was that if I have an instance method and an extension method with the same signature, it's the instance method that gets called.

But apparently not in my test - if I put a break point on the instance method in my stub it never gets called, and the test fails with an error as it's still calling into the third party extension method.

Can anyone explain why this should be the case? I'm aware of, though not used, Microsoft Fakes (using a shim) which might be the way to solve this problem. But I can't see why this stubbing method isn't working. Thanks.

Community
  • 1
  • 1
Andy Butland
  • 438
  • 4
  • 17
  • Are the methods exactly the same include all parameters type and return value type? – Aik Mar 10 '14 at 09:24
  • The third party library doesn't know about your added instance method. It's not a virtual method you can override in your own class. – Rawling Mar 10 '14 at 09:26
  • @Aik - yes, they are. – Andy Butland Mar 10 '14 at 09:26
  • @Rawling - that's true, and its maybe me just expecting something that isn't going to happen; but I'm not overriding it (I'm implementing an interface, not sub-classing a base class). It seemed to me that at runtime, my test would have an instance of my stubbed class, which has an instance method with the matching signature - and hence should call that in preference to the extension method from the third party library. – Andy Butland Mar 10 '14 at 09:30
  • 1
    For your desired behaviour you have to work with virtual function. Sadly the extension method call is static call and there is no way how to replace it once it is compiled – Aik Mar 10 '14 at 09:33

1 Answers1

2

Stubs do not substitute static or extension methods. You need to use shims. See https://stacktoheap.com/blog/2012/11/11/testing-extension-methods-with-microsoft-fakes/

Michael Freidgeim
  • 26,542
  • 16
  • 152
  • 170