Monday, August 8, 2011

Junit: Testing Private Methods.

I was researching on how to test private methods in junit and did a quick query. Few notable search results pointed me to a PrivateAccessor class and in particular invoke method. This class is available inside junit-addon jar available at the link.

So the basic idea is that this class bypasses Java modifier security/access specifier on methods and fields.
Following are the required input parameters:
1) Object which contains private methods.
2) Private method to be tested.
3) Parameter argument type array passed to that private method.
4) Values array passed to that private method.

The invoke method returns an Object, which I found that it contains the return value of the private method. Straightforward, isn't!

Following is the snippet of code, I used this class as follows:

package mycompany;

import org.junit.Test;
import static org.junit.Assert.assertTrue;
import junitx.util.PrivateAccessor;

import java.io.File;

public class MCExtractorTest {

 @Test
 public void testMerge() throws Exception {
  MCExtractor extractor = new MCExtractor("/prod/medlineMatch.xml", "/home/amrut/els/medline/cip");
  extractor.merge();
 }

 @Test
 public void testGetCollecIdFromDatabase() throws Throwable {
  MCExtractor extractor = new MCExtractor("/prod/medlineMatch.xml", "/home/amrut/els/medline/cip");
  Object object = PrivateAccessor.invoke(extractor, "getCollecIdFromDatabase", new Class[]{String.class}, new String[]{"S00090X"});
  assertTrue(object.toString().equals("JL-1s20S000071-1s20S00090X"));
 }
}

No comments:

Post a Comment