How can you mock a private method call that uses a non accessible enum as a method parameter?

2 posts, 0 answers
  1. Arthur
    Arthur avatar
    2 posts
    Member since:
    Jun 2011

    Posted 28 Oct 2015 Link to this post

     Here is an example of what I'd like to mock up?  

    namespace ExternalAssembly
        internal enum HintArg { Flag1,Flag2,Flag3}
        public class ExternalClass
            private int MethodToMock(string name, HintArg hint, out string result)
                result ="I want to override this";
                return 0;

    In this example what I'd like to have is a setup that will call the original MethodToMock on everything except when I have a specific name match?

     I have something along the lines of:

    string mockName="mockName";
    string mockResult ="new result";

    I'm just not sure how to specify the arg expression when the type is an internal that my invoking assembly is not friends with?






  2. Stefan
    Stefan avatar
    198 posts

    Posted 29 Oct 2015 Link to this post

    Hello Arthur,

    This is a complicated use case, because it combines matching by value, an out argument and a non-accessible parameter type.

    The current API is not expressive enough to cover this case properly, but you can use the available primitives to get the desired behavior:
    public delegate int MethodToMockDelegate(string name, object hint, out string result);
    string mockName="mockName";
    string mockResult = "new result";
    Mock.NonPublic.Arrange<int>(typeof(ExternalClass), "MethodToMock")
        .When((string name, object hint, string result) => name == mockName)
        .Returns(new MethodToMockDelegate(string name, object hint, out string result)
            result = mockResult;
            return 0;
    So, using the .When() clause, you can hide the private type behind an object. This approach will only work if there is a single method named MethodToMock. If there are overloads, you will need to obtain the MethodInfo for that method and pass that in place of the method name in the Arrange.

    Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Feedback Portal and vote to affect the priority of the items
  3. DevCraft R3 2016 release webinar banner
Back to Top