Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use Moq to mock an extension method?

I am writing a test that depends on the results of an extension method but I don't want a future failure of that extension method to ever break this test. Mocking that result seemed the obvious choice but Moq doesn't seem to offer a way to override a static method (a requirement for an extension method). There is a similar idea with Moq.Protected and Moq.Stub, but they don't seem to offer anything for this scenario. Am I missing something or should I be going about this a different way?

Here is a trivial example that fails with the usual "Invalid expectation on a non-overridable member". This is a bad example of needing to mock an extension method, but it should do.

public class SomeType {     int Id { get; set; } }  var ListMock = new Mock<List<SomeType>>(); ListMock.Expect(l => l.FirstOrDefault(st => st.Id == 5))         .Returns(new SomeType { Id = 5 }); 

As for any TypeMock junkies that might suggest I use Isolator instead: I appreciate the effort since it looks like TypeMock could do the job blindfolded and inebriated, but our budget isn't increasing any time soon.

like image 661
patridge Avatar asked Feb 18 '09 17:02

patridge


People also ask

How do you declare an extension method?

An extension method must be defined in a top-level static class. An extension method with the same name and signature as an instance method will not be called. Extension methods cannot be used to override existing methods. The concept of extension methods cannot be applied to fields, properties or events.

How do you implement and call a custom extension method?

To define and call the extension methodDefine a static class to contain the extension method. The class must be visible to client code. For more information about accessibility rules, see Access Modifiers. Implement the extension method as a static method with at least the same visibility as the containing class.


1 Answers

Extension methods are just static methods in disguise. Mocking frameworks like Moq or Rhinomocks can only create mock instances of objects, this means mocking static methods is not possible.

like image 175
Mendelt Avatar answered Sep 30 '22 15:09

Mendelt