Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

It is a good Practice to change Private method to Public for Unit Test Case

Recently, I was working on the unit test case of legacy code, while writing test cases, I am come up with a problem.

Since I am writing unit test case not integration test. The problem is with private method. In our code a public method is dependent on 5 private method.

For unit test case, I required to give fake implementation of private method, but since method is private, I can't able to-do so. Because MOQ mocking framework did not support the mocking functionality of private method. and even I can't able to write test case of private method.

Possible approach I was thinking

Move all private method in different class. and make them public and also create an interface of this class. In this way I can able to give fake implementation at run-time because now we have Interface of the class.

But the problem in this approach is I need to make this private method to public just for unit test case. so it is a good practice to make it public.

like image 531
Shobhit Walia Avatar asked Sep 02 '25 10:09

Shobhit Walia


1 Answers

I do commonly split classes when I start seeing myself writing a lot of private methods. But you have a couple of options:

  1. Fully test the public interface only. You should cover your private methods as a matter of course.

    • Effective for classes where it makes sense for all the functionality to remain together. That is, the class is already well abstracted and has a Single Responsibility.
    • Can be a pain if keeping these private methods in the class means more mocking and setup is required for every case.
  2. You can make your private methods internal and specify your test project as a friend assembly. Then they can be unit tested directly.

    • This can be effective again when it doesn't make sense to split the class.
    • This has an advantage over testing the public interface when you have a bunch of private methods called by one public method. If you're wanting to test one part of one of the private methods, you don't have to set up everything required by the public method. This also makes things easier to understand and debug.
  3. The solution you already thought of to just split up the class. Sometimes code being difficult to test indicates that there's a class inside trying to break out.

    • If you can group some or all of your private functionality into a named entity, you might want to pull it apart. Especially if you have other circumstances where you might be able to reuse such a class.
    • This is also a good option if your original class has a large dependencies list and you can reduce it with this option.
like image 186
Tracy Moody Avatar answered Sep 05 '25 00:09

Tracy Moody



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!