'Can't seem to be able to use Invoke (reflection method) with Returns (from NSubstitute), so how else can I mock a protected method?

I am trying to use reflection within my unit tests in order to call a protected method.

The protected method takes an argument that can be any string and I am trying to mock the response.

I would normally do this (if the method was public, not protected):

controller.SomeMethod(Arg.Any<string>()).Returns("some text");

Now, since SomeMethod is protected, the above won't work. So, I tried: MethodInfo dynMethod = controller.GetType().GetMethod("SomeMethod", BindingFlags.NonPublic | BindingFlags.Instance);

Followed by

dynMethod.Invoke(controller, new object[] {}).Returns("some text"); // error on this line: "Member Invoke cannot be intercepted. Only interface members and virtual, overriding, and abstract members can be intercepted."

Also, I don't know how to specify that the parameter can be any string when I call the method through reflection.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source