Last post Feb 25, 2020 03:25 PM by mgebhard
Feb 21, 2020 06:16 AM|ProgMaster|LINK
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.
Feb 25, 2020 07:51 AM|Mikesdotnetting|LINK
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
Feb 25, 2020 01:04 PM|ProgMaster|LINK
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.
Feb 25, 2020 03:25 PM|mgebhard|LINK
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