0

I am writing a Junit for a method with multiple parameters and having private access specifier. I am using Java reflection to achieve this. However, one of the parameter for this private method is private class. I am doing below:

ClassHavingPrivateMethod object = new ClassHavingPrivateMethod();
object.getClass().getDeclaredMethod(PRIVATE_METHOD_NAME, Param1.class, <This parameter is a private class Inside ClassHavingPrivateMethod>)

How can I proceed?

EDIT

I agree on the point that I should not write a test case for a private method with reflection and it should always be accessed through a wrapper public method. However, is there any way to achieve the above objective through reflection. Even though, I am not going to write my test case through reflection but I am eager to know about it.

Any help is really appreciated.

Somnath Musib
  • 3,548
  • 3
  • 34
  • 47
  • 3
    Why do you need to test private methods? Can't they be exercised through the public API? – Thilo Jan 15 '15 at 11:09
  • 3
    Be careful when testing private methods. You'll quickly end up testing the implementation rather than the behaviour. – NilsH Jan 15 '15 at 11:10
  • Here is some discussion if private methods should be tested directly: http://stackoverflow.com/questions/105007/should-i-test-private-methods-or-only-public-ones?lq=1 – Thilo Jan 15 '15 at 11:11
  • @Thilo : Yes, there is a wrapper public method for this private method. But If i try to call this wrapper, I have to do a lot of extra set up and that is not inside my JUnit testing scope. Actually, this method is inside a JmsListner onMessage() method. This onMessage() is public method. – Somnath Musib Jan 15 '15 at 11:17
  • @NilsH Thanks for the suggestion, I will keep it in mind. – Somnath Musib Jan 15 '15 at 11:19
  • " I have to do a lot of extra set up and that is not inside my JUnit testing scope.". That is a common problem. Ideally, these "glue" classes (like the JmsListener) don't do much themselves and just act as facades to otherwise testable code. Real-life is seldom ideal, though. Maybe the class can be refactored so that the "juicy parts" that you want to test are package-private? Then they are still hidden from the public interface but accessible to unit tests? – Thilo Jan 15 '15 at 11:24

1 Answers1

2

One of the way you can try by changing the access from private to default. By changing the access level to default the method can be accessed only from the same package (still restricted access) on the other hand since your test class and class under test will be under same package , the test class can call that method directly, without doing any trick.

Example :

package com.test;

class SomeClass {
  String defaultMethod(){
   ...
  }
}


package com.test;

class SomeClassTest {
  public void testDefaultMethod(){
    SomeClass testObject = new SomeClass();
    testObject.defaultMethod();
  }
}

Hope it will help.

Manmay
  • 835
  • 7
  • 11