Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
Win a copy of OCP Java SE 8 Programmer II Exam Study Guide this week in the OCP forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Testing private methods using Reflection API  RSS feed

 
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ranchers,
I have tested private methods using reflection API.
Now I want to test a private method which inturens calls another private method.
Sure enough I get InvocationTargetException when I try to run this test.

for example,



in the above ex. i can run tests on privateMethodB(), but not on privateMethodA().
SO what do I do using reflection to test privateMethodA() ?

suggestions please...

 
Ranch Hand
Posts: 378
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Isn't it that your method is throwing an Exception? Did you call getCause on the InvocationTargetException to see what the wrapped Exception is?
 
praveen Shangunathan
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
the JUnit test throws an InvocationTargetException. this is because from the JUnit using reflection I call methodA. but since methodA calls methodB and that is private as well, an exception is thrown.
 
Gamini Sirisena
Ranch Hand
Posts: 378
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Have a look here

Call the getCause method and check the stack trace on the returned Throwable. It should give the cause as to why the InvocationTargetException was thrown.
 
praveen Shangunathan
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
the InvocationTargetException is thrown because i do not have permission to access privaMethodB when i am running private MehodA.
I wasnt o know how to avoid it.
 
Rancher
Posts: 42975
76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
See here for a discussion on how to access private fields/methods using reflection.
 
praveen Shangunathan
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks Ulf and Sirisena.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!