Mocking Extension Methods With Moq

How do I use Moq to mock an extension method?

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.

How to properly mock extension methods with generics in xUnit?

Assuming you are using MOQ, do not try to mock the extension method.

Since you control the code of the extension method then mock a safe path through the extension method.

The extension uses GetAsync in this case and that is what needs to be mocked assuming that is not an extension as well.

//...

_repository
.Setup(x => x.GetAsync(It.IsAny<Guid>()))
.ReturnsAsync(GetSamplePhase(newGuid));

//...

It will allow the test when exercised to go through GetActiveAsync code and if it fails, also throw the Exceptions etc as described in the code.

Mock extension methods IElasticClient

Per @Olegl answer. It is not possible to Mock extension methods. You need to refactor and get rid of extension methods in order to make it testable

More info here



Related Topics



Leave a reply



Submit