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
Split a String by Another String in C#
What Does the @ Symbol Before a Variable Name Mean in C#
Using Async/Await For Multiple Tasks
What Is App.Config in C#.Net - How to Use It
How to Create Linq Expression Tree to Select an Anonymous Type
Get String Between Two Strings in a String
Ipc Mechanisms in C# - Usage and Best Practices
What Does "Use of Unassigned Local Variable" Mean
Cast Generic≪Derived≫ to Generic≪Base≫
How to Update the Current Line in a C# Windows Console App
Deserialize Json to C# Classes
.Net Process.Start Default Directory
How to Spawn a Process and Capture Its Stdout in .Net
How to Use Optional Parameters in C#