Wednesday, June 04, 2008

Accessing private methods using JUNIT

If you want to test private method of class which has object's as arguments here is the example to how do it.

First SampleObject



package com.sathish;
public class Sample {
public String example;
public String example1;
/**
* @return Returns the example.
*/
public String getExample() {
return example;
}
/**
* @param example The example to set.
*/
public void setExample(String example) {
this.example = example;
}
/**
* @return Returns the example1.
*/
public String getExample1() {
return example1;
}
/**
* @param example1 The example1 to set.
*/
public void setExample1(String example1) {
this.example1 = example1;
}
}



 


Second the Class with private method

package com.sathish;
public class SampleMain {

private Sample getSampleValues(Sample sample)
{
System.
out.println(" Sample Values Setting in SampleMain"+sample.getExample());
return sample;
}
}


 



Third JUNIT Class File



package com.sathish;

import java.lang.reflect.Method;
import junit.framework.TestCase;

public class SampleTest extends TestCase {
/*
* @see TestCase#setUp()
*/
private Sample sample;
private SampleMain sampleMain;
protected void setUp() throws Exception {

sample=
new Sample();
sampleMain=
new SampleMain();
}
public final void testGetSampleValues()
{
try
{
sample.setExample(
" setting Example 1");
final Method[] methods = SampleMain.
class.getDeclaredMethods();
for (int i = 0; i < methods.length; i++) {
if (methods[i].getName().equals("getSampleValues")) {
final Object
params[] = {sample};
methods[i].setAccessible(
true);
sample = (Sample)methods[i].invoke(sampleMain,
params);
}
}
}
catch(Exception exception)
{
exception.printStackTrace();
}
}
}


 


 

If you check in the JUNIT class, we will be using reflections to find the method and invoke .getDeclaredMethods() method will give array of methods declared in the SampleMain class looping through the methods we are getting the method which has declared private here getSampleValues.

Then we are preparing arguments, setting that particular method accessible and then invoking method with arguments



finally this the output after running the JUNIT file

Sample Values Setting in SampleMain setting Example 1

0 comments: