locked
Unit Testing Behavior of a Private Method RRS feed

  • Question

  • User931778073 posted

    I don't know if this is the right place to ask question related to unit testing but here goes. Suppose I have a public method that calls a private method, how should I go about unit testing this public method even though I cannot mock the private method within it? I know this question probably has been asked hundreds of time but I still don't know what the accepted answer is.

    I have searched online and found posts where some people said not to even test private methods but others said to test their behaviors instead.  Can someone please explain what that even mean. How does one test the behavior of a method without going into the method itself? Please give an example of how this is done.

    Friday, February 21, 2020 6:16 AM

All replies

  • User-821857111 posted

    You can use the PrivateObject type to wrap your class and call the private method. See the highest voted answer to this question: https://stackoverflow.com/questions/9122708/unit-testing-private-methods-in-c-sharp

    As to whether you should do this, that's another matter. Some people see the inclusion of private methods in a class as going against the Single Responsibility Principal. However, I've seen enough private methods in classes in the source code of the ASP.NET framework to question the validity of that as a broad statement. 

    You can test the behaviour of private methods by testing their effect on whatever calls the private method. For example, if the private method performs calculations on behalf of an object, you test that the result of the calculation on the calling object is correct. 

    Tuesday, February 25, 2020 7:51 AM
  • User931778073 posted

    Hi Mike, Thanks for your response. Unfortunately I'm using NUnit which does not have PrivateObject. Also I'm calling a service to get data and I'm not sure how I would mock something like a service call.

    Tuesday, February 25, 2020 1:04 PM
  • User475983607 posted

    ProgMaster

    Unfortunately I'm using NUnit which does not have PrivateObject. Also I'm calling a service to get data and I'm not sure how I would mock something like a service call.

    Calling a service is not a unit test, it's an integration test.  If you are trying to test business operation on the service result then you should mock the service and return a result that you control.  You get to format the data to pass and/or fail the unit test.

    Tuesday, February 25, 2020 3:25 PM