Testing private helper methods
3 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   David_Bates
Posted On:   Saturday, March 1, 2003 08:48 AM

OK. I'm writing a class 'MyClass' which exposes a number of public methods: 'pub1()', 'pub2()' and 'pub3()'. However, all of these methods use a protected helper method 'proHelper()'. How can I test the protected helper methods using JUnit? I don't want to put the JUnit test class in the same package as the class (I consider that bad form. The test classes should be in a mirror hierarchy to the application packages). I have a couple of ideas, the best of which is: Create the test class called 'TestMyClass' in the test hierarchy. This class contains an inner class 'pubMyClass' which is a subclass of 'MyClass'. This class overrides the protected method: public void proH   More>>

OK. I'm writing a class 'MyClass' which exposes a number of public methods: 'pub1()', 'pub2()' and 'pub3()'. However, all of these methods use a protected helper method 'proHelper()'. How can I test the protected helper methods using JUnit? I don't want to put the JUnit test class in the same package as the class (I consider that bad form. The test classes should be in a mirror hierarchy to the application packages).



I have a couple of ideas, the best of which is:




Create the test class called 'TestMyClass' in the test hierarchy. This class contains an inner class 'pubMyClass' which is a subclass of 'MyClass'. This class overrides the protected method:

			
				
public void proHelper() {
super.proHelper();
}

The method 'proHelper()' is now visible to the class 'TestMyClass'.




If anyone has any thoughts on this, I'd like to hear them. Also, I'd be interested to hear if anyone has any bright ideas about testing private helper methods.



Cheers,



David.    <<Less

Re: Testing private helper methods

Posted By:   Bryan_Dollery  
Posted On:   Monday, March 3, 2003 09:17 PM

Hi David,


I cover this issue, and others, in a DevX article published last year. Read it here.


Cheers,


Bryan

Re: Testing private helper methods

Posted By:   Lasse_Koskela  
Posted On:   Sunday, March 2, 2003 01:03 AM

My opinion is that unit tests should be written only for the public methods (code to interface, not to implementation), except when the private/protected method is relatively complex and essential.


Having that said, I remember seeing a helper class for writing tests for private/protected members/methods using reflection. Unfortunately I don't have it, but I'd suggest to take a Google session or just browse the Reflection API docs.

Re: Testing private helper methods

Posted By:   Anonymous  
Posted On:   Sunday, March 2, 2003 12:58 AM

My first question is: why do you feel you need to test it?
About | Sitemap | Contact