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);
}
}
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!