Showing posts with label private. Show all posts
Showing posts with label private. Show all posts

Wednesday, September 14, 2011

JUnit Testcase for private method and variable

Example of writing JUnit Test-cases for private members of a class


// ClassA.java
public class ClassA {
  
    private int privateInteger = -1;
    private String privateString;

    private void methodA(String s, int a, int b) {
        this.privateString = s;
        this.privateInteger = a * b;      
    }
}

//ClassATest.java
@org.junit.Test
    public void testMethodA() {
       
        ClassA classA = new ClassA();
        java.lang.reflect.Method methodA;
        try {
            methodA = ClassA.class.getDeclaredMethod("methodA", String.class, int.class, int.class);
       
            java.lang.reflect.Field privateIntField = ClassA.class.getDeclaredField("privateInteger");
           
            methodA.setAccessible(true);
            privateIntField.setAccessible(true);
   
            methodA.invoke(classA, "Hi", 2, 3);
           
            org.junit.Assert.assertEquals(6, privateIntField.getInt(classA));      
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (java.lang.reflect.InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }