Loading
 
What's Next: View All Tutorial →

How to test Private Method in java - Junit

In this article, we will learn how to test private/protected method using the Reflection method Java Class file package com.mycompany.app; public class Car { private boolean putBreak(int gearNumber) { if (gearNumber <= 0) ...

Published Date: 29/04/2015  Last Modified Date: 29/04/2015    New Post



In this article, we will learn how to test private/protected method using the Reflection method

Java Class file

package com.mycompany.app;

public class Car {

    private boolean putBreak(int gearNumber) {
        if (gearNumber <= 0) {
            return false;
        }
        return true;
    }

    protected String takeReverese(String direction, String roadType) {
        if ("left".equals(direction) && roadType != null) {
            return "Go";
        }
        return "Don't allow";
    }
}

Test File

package com.mycompany.app;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;

public class CarTest {

    public CarTest() {
    }

    @BeforeClass
    public static void setUpClass() {
    }

    @AfterClass
    public static void tearDownClass() {
    }

    @Before
    public void setUp() {
    }

    @After
    public void tearDown() {
    }

    @Test
    public void testPrivateWithOneArgument() throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        Car c = new Car();
        Method method = Car.class.getDeclaredMethod("putBreak", Integer.TYPE);

        method.setAccessible(true);

        Boolean acutalResult = (Boolean) method.invoke(c, 1);
        assertEquals(acutalResult, true);

        acutalResult = (Boolean) method.invoke(c, 0);
        assertEquals(acutalResult, false);
    }

    @Test
    public void testPrivateWithTwoArgument() throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        Car c = new Car();
        Method method = Car.class.getDeclaredMethod("takeReverese", String.class, String.class);

        method.setAccessible(true);

        String acutalResult = (String) method.invoke(c, "left", "SUV");
        assertEquals(acutalResult, "Go");

        acutalResult = (String) method.invoke(c, "left", null);
        assertEquals(acutalResult, "Don't allow");
    }

}


method.setAccessible(true); - To make it visible
 
Awaiting for Administrator approval





Tags: JUnit

← Back to list


Related Post




×