Java: Testing Private Methods in JUnit using reflection API Example


Student Class with Private Method:
public class Student {

    private String name;
    private int score;

    public Student(String name, int score) {
        this.name = name;
        this.score = score;
    }

    public String getName() {
        return name;
    }

    public int getScore() {
        return score;
    }

    private String getGrade() { //private method
        if (score >= 90) {
            return "A";
        } else if (score >= 80) {
            return "B";
        } else if (score >= 70) {
            return "C";
        } else if (score >= 50) {
            return "D";
        } else {
            return "E";
        }
    }
}

Junit Test Code:
import org.junit.Test;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import static org.junit.Assert.assertEquals;

public class StudentTest {
    @Test
    public void testGetGrade() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        
       Student student = new Student("Mike Kane", 90);

        // Using reflection to access private method
        Method getGradeMethod = Student.class.getDeclaredMethod("getGrade");
        getGradeMethod.setAccessible(true);

        // Accessing Private getGradeMethod method
        String grade = (String) getGradeMethod.invoke(student);

        // Asserting the result of the private method
        assertEquals("A", grade);
    }
}

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap