• Post Reply Bookmark Topic Watch Topic
  • New Topic

Test private method with primitive parameters in JUnit  RSS feed

 
Abhra Kar
Ranch Hand
Posts: 159
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My To be tested method is division --


and test method --


If I replace Line 1 with Line 2 then execute properly.
But if I don't I get NoSuchMethodExcecption

getDeclaredMethod doesn't allow primitive type.

With out modifying the to be tested method how can I execute the test case?

Thanks
Abhra
 
Tim Cooke
Marshal
Posts: 4039
239
Clojure IntelliJ IDE Java
  • Likes 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your MyClass3 is completely useless because it has no public methods in it, therefore there's no point in testing it at all. For the remainder of this discussion I'm going to assume that you have other public methods in that class you haven't included that make use of this private division method.

I don't write unit tests for private methods, and I certainly don't use reflection to gain access to a private method. That's just nasty. Have a think about what you define as a 'unit' for your unit tests. I might consider a public method a unit, where that unit might include calls to one or more private methods.
 
Abhra Kar
Ranch Hand
Posts: 159
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Tim for your suggestions.
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16057
88
Android IntelliJ IDE Java Scala Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you should have used int.class instead of Integer.class (yes, that works, and although int is a primitive type, int.class is still valid).

But I agree with Tim that you shouldn't need to write unit tests for private methods.
 
Junilu Lacar
Sheriff
Posts: 11476
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That test is like a doctor performing open heart surgery so he can check the patient's pulse. Totally unnecessarily invasive.
 
Rob Spoor
Sheriff
Posts: 21131
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If this method contains so much logic that you feel you need to test it, you should make it package private. That way your test class can access it (assuming you put your test class in the same package).
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!