This is a migrated thread and some comments may be shown as answers.

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

1 Answer 166 Views
General Discussions
This is a migrated thread and some comments may be shown as answers.
Arthur
Top achievements
Rank 1
Arthur asked on 28 Oct 2015, 11:55 PM

 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";
Mock.NonPublic.Arrange(typeof(ExternalClass),"MethodToMock",mockName,ArgExpr.IsAny<HintArg>(),ArgExpr.Out<string>(newResult).Returns(0);

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?

 

 

 

 

 

1 Answer, 1 is accepted

Sort by
0
Stefan
Telerik team
answered on 29 Oct 2015, 03:52 PM
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.


Regards,
Stefan
Telerik
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
Tags
General Discussions
Asked by
Arthur
Top achievements
Rank 1
Answers by
Stefan
Telerik team
Share this question
or