Social Share

How to write the test cases for private methods?

How to write the test cases for private methods?

Most of us struck while writing the test cases with the private methods and thinks about the how to write test cases for private methods. To test these methods some of the possible methods are shown below,

The following are the methods for writing the test cases,

1. Test these methods using the public methods. The public method that access the private methods has to be tested.

In this method the problem is that some times the scenario can be like we could not have a public method that returns some value. At that case even though we are able to invoke the private methods its waste to invoke as it cannot be tested properly.

2. Using the reflection concept to invoke the private methods. This works very well. I will show you an example here for your understanding of how to use the reflection in testing the private methods.

Consider the private methods inside the target.class as shown below,

class Target
       private int calculateAdd(int number1,int number2)
              return number1 + number2;

Now create a test class in the android test folder.

class TargetTestCase extends TestCase
        public void setup()
        public void testCalculateAdd()
                 Target target = new Target();
                  Class<T>[] paramsTypes = new Class[] {Integer.class, Integer.class}; 
                  Method calculateMethod = Target.class.getDeclaredMethods("calculateAdd",paramsTypes);

                   int number1 = 2;
                   int number2 = 5;
                   int returnVal = (int)calculateMethod.invoke(target,number1,number2);

Hope you got the answer on How to write the test cases for private methods? in junit either in android or in any language.

Follow the post! Happy reading...! :-)


Latest Technology Videos

Popular posts