Geeks With Blogs
Abhishek Anand Bits & Bytes about .net technology framework.

Moq provides an additional overload for the Returns method that takes a lambda expression with the same parameters as the method signature. When this overload is used, Moq will inject the parameters passed to the Setup method into the Returns as its lambda expression parameters.

Note: The parameters for the lambda expression must match up in both number and ordering to the method signature.

Example 1:

       public interface ITestInterface

 {

     string SomeMethod(string str);

 }

                  …

        mockTestInterface.Setup(i => i.SomeMethod(It.IsAny<string>()))
                 .Returns((string str) => str);
        Assert.AreEqual("hello", mockTestInterface.Object.SomeMethod("hello"));
         //Test Passes
 

 Example 2:

        public interface ITestInterface

    {

SomeComplexType SomeMethod(SomeComplexType complex, SomeOtherComplexType other);

    }   

                              …

                 mockTestInterface.Setup(i => i.SomeMethod(It.IsAny<SomeComplexType>(), It.IsAny<SomeOtherComplexType>()))

.Returns((SomeComplexType c, SomeOtherComplexType o) => c);

        //Assert

            …

Posted on Monday, November 18, 2013 6:27 PM .net , unit testing , moq , mocking | Back to top


Comments on this post: Moq – Return a Parameter

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © Abhishek Anand | Powered by: GeeksWithBlogs.net