C #: Denying and testing protected (or private) methods in private classes - approaches

I have a private class with protected methods whose behavior I want to test. This makes direct testing difficult, and it is difficult to mock.

This is in a code base that was not developed in TDD, and now I am adding unit tests for specific functions.

What are the common approaches in this case? At the moment I have:

  • Class not printed. Then create a proxy or adapter obtained from the class in our test code to tunnel access to the protected method.
  • Change the behavior in the protected method to a delegate / functor and retype it. Then check for fact-based independent behavior.
  • Testing by calling the closest public method in the inheritance hierarchy using a protected method. Potentially leads to a lot of ridicule and exposure to risk when the code is different from the one under the control of the test - creating fragile tests.
  • Use reflection to access a protected method. Then call it directly.

Is there any more?

+4
source share
5 answers

A protected method in a private class is actually the same as private (I think if you seal a derived class where the base class has the protected member, this can occur naturally.)

And there are no exact private testing methods. Since they do not have public behavior, other than what is available using the public methods of the defining class, their behavior should be checked by testing the public methods.

+7
source

Microsoft Moles helps make fun of non-printable classes with non-virtual methods. It cannot mock private methods, but it is redundant because you can make fun of higher-level public methods that are used outside a particular class, and you can emulate all the necessary actions by mocking one public method.

And why should you test private / protected methods? You can use internal methods and InternalVisibleToAttribute for this . But in general, you should only test public behavior (i.e. only open interface).

+3
source

I would go for the second option, believing that you have the opportunity to make the changes easy enough. Given that if you cannot verify what the protected / private method does through the public interface, it probably does not comply with the principle of single responsibility in any case, and probably the code can be divided into two classes and use composition instead.

+2
source

You can use some framework for ridicule - for example, JustMock (according to Telerik) supports the layout of private private methods ... Unfortunately, this part is from JustMock, I think, but at least you can try the trial version.

+1
source

You can use the JustMock environment. For instance:

 double value = 0; var fakeFilterSetHelper = Mock.Create<FilterSetHelper>(Behavior.CallOriginal); Mock.NonPublic.Arrange<double>(fakeFilterSetHelper, memberName: "GetPriceRangeFromSession").Returns(value); 
+1
source

Source: https://habr.com/ru/post/1336318/


All Articles