Issues in writing test case for a private method

74 views Asked by At

I am trying to write a test case for params method in the below class.

Problems while writing a JUnit test case:

The problem is that the method is private and inside the method it calls for super class methods. I tried using EasyMock where I will be able to supress the calls to super class constructors

CustomListener customListenerMock=createMock(CustomListener.class);
    expect(customListenerMock.getParam("CHECK_INTEGRITY")).andReturn(null);
    expect(customListenerMock.getParam("WRITE_ANSWER")).andReturn(null);    

The document says that I will be able to supress these methods when they are called and can give the specified output i.e null in this case.

Now My problem is how do I invoke the private method for testing? I tried by using reflection API, but It does not work as desired.

code:

 Method InitialiseSecurityConfiguration = Listener .class.getDeclaredMethod(methodToTest, null);
    InitialiseSecurityConfiguration.setAccessible(true);
    InitialiseSecurityConfiguration.invoke(fileListenerObj);

When I invoke with reflection API, these methods are called just like that and super clas methods are not supressed as desired.

Note: I am using a legacy application, and not allowed to change the visibility of my methods.

class Listener extends CustomListener{

 /*
      Some More methods
 */

private boolean params()
      {
        String integrity = "";
        String sWAnswer = "";
        try
        {
          try
          {
            integrity = super.getParam("CHECK_INTEGRITY");
            sWAnswer = super.getParam("WRITE_ANSWER");


            **Some Business Logic** 

          super.info("Request Directory  : " + sRequestPath);
          super.info("Response Directory : " + sResponsePath);
          super.info("Error Directory    : " + sErrorPath);
          }
        }
        catch (Exception ex)
        {
          bCheck = false;
        }
        return bCheck;

              }//closing the method params
}//Closing Listener class     
1

There are 1 answers

0
Phil Anderson On BEST ANSWER

I would write tests for the public methods that call the private method you're interested in.

As a general rule, it's good practise to write unit tests against the public API of a class so that the implementation (i.e. private methods) can be changed without having to change the tests.

The public API is how the class is used, so that's what should be tested.