Progress Telerik JustMock

Mock Extension Methods

Nasa, Visa, Microsoft Fox, Samsung, IBM World Bank Group, Volvo
  • Mocking Extension Methods Overview

    Extension methods are a special kind of static methods that are called as if they were instance methods on the extended type.

    Mocking extension methods is similar to mocking any instance method. The only difference is that we don’t need a Mock.Create<T>() call to initialize the class for mocking as extension mocking is by default partial.

    public static class FooExtensions
    {
        public static string Echo(this Foo foo, string value)
        {
            return value;
        }
    }
     
    ...
     
    [TestMethod]
    public void ShouldAssertExtensionMethodMockingWithArguments()
    {
        string expected = "bar";
     
        // ARRANGE
        var foo = new Foo();
     
        // Arranging: When the extension method foo.Echo() is called with any string argument,
        //            it should return expected.
        Mock.Arrange(() => foo.Echo(Arg.IsAny<string>())).Returns(expected);
     
        // ACT
        string actual = foo.Echo("hello");
     
        // ASSERT
        Assert.AreEqual(expected, actual);
    }

    Mock extension methods documentation
Background-NextSteps

Next Steps

See Plans & Pricing

Purchase individual products or any of the bundles

Download Free Trial

With dedicated technical support.