javaprivatejunit3

How can I write a JUnit test of a private function which is returning a Boolean?


I have written a JUnit test for a private function which is returning String. And it is working fine.

public void test2() throws Exception
{
    MyHandler handler = new MyHandler();
    Method privateStringMethod = MyHandler.class.getDeclaredMethod("getName", String.class);
    privateStringMethod.setAccessible(true);
    String s = (String) privateStringMethod.invoke(handler, 852l);
    assertNotNull(s);
}

I have one more function which returns boolean but this is not working. But in that I am getting a compile time error saying Cannot cast from Object to boolean.

public void test1() throws Exception
{
    MyHandler handler = new MyHandler();
    Method privateStringMethod = MyHandler.class.getDeclaredMethod("isvalid", Long.class);
    privateStringMethod.setAccessible(true);
    boolean s = (boolean) privateStringMethod.invoke(handler, 852l);
    assertNotNull(s);
}

How can I run?


Solution

  • The returnvalue will be 'autoboxed' to an Boolean object. Since a primitive can't be null, you mustn't test against null. Even .booleanValue() mustn't be called, because of Autoboxing.

    But I'm of the same opinion as @alex.p, regarding testing private methods.

    public class Snippet {
    
        @Test
        public void test1() throws Exception {
            final MyHandler handler = new MyHandler();
            final Method privateStringMethod = MyHandler.class.getDeclaredMethod("isvalid");
            privateStringMethod.setAccessible(true);
            final Boolean s = (Boolean) privateStringMethod.invoke(handler);
            Assert.assertTrue(s.booleanValue());
        }
    
        class MyHandler {
            private boolean isvalid() {
                return false;
            }
        }
    }