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!
More Posts related to Java,
- Java equals method - Tutorial
- Unbound classpath container: JRE System Library [JavaSE-1.7]
- Spring Boot: @RequestBody not applicable to method
- Java 8: Steam map with Code Examples
- Java Program: Random Number Generator
- Java java.time.Clock class code examples [Java Date Time API]
- Fix: type argument is not within bounds of type-variable T
- [Fix] java.net.MalformedURLException: unknown protocol
- Java 7 addSuppression() and getSuppression() Exception Handling
- Convert Java Array to ArrayList Code Example
- How to Word-Warp Console logs in IntelliJ
- Ways Compare Dates in Java Programming with Examples
- Remove Trailing zeros BigDecimal Java
- CRUD operations in Spring Boot + JDBC
- [Java Threads] Should we extend Thread Class or implement Runnable interface
- Json Serialization and Deserialization using Java Jackson
- Create simple struts2 project using maven commands
- How to install Java OpenJDK 11 on Alpine Linux
- Unsupported major.minor version 52.0 in java
- Error: Can not find the tag library descriptor for
- Java: Convert String to Binary
- How to run Java Unit Test cases with Apache Maven?
- Java: Testing Private Methods in JUnit using reflection API Example
- Java JDBC Connection with MySQL Driver in VS Code + Troubleshooting
- Java Join Strings with Comma Separator
More Posts:
- [Fix] Steam Friends Network Unreachable Error - HowTos
- How to Add Tab in Python - Python
- How to un-hide tab bar in notepad++ - NotepadPlusPlus
- Docker Desktop needs privileged access macOS - MacOS
- Python print() function without a newline using the end parameter - Python
- RabbitMQ Java Spring Boot Application Properties List - Java
- How to stop or quit cat command? - HowTos
- [fix] Docker Desktop App not starting on Mac (macOS) - Docker