Issue
Here is the private method I am trying to test:
private int privateMethod(int[] numbers) {
var sum = 0;
for (int number : numbers) {
sum += number;
}
return sum;
}
I am doing this in Java 11.
And following is my test using Junit 5:
import org.junit.jupiter.api.Test;
import org.junit.platform.commons.function.Try;
import java.lang.reflect.Method;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.platform.commons.util.ReflectionUtils.*;
@Test
public void assertPrivateMethodExistence() {
final String methodName = "privateMethod";
final Optional<Class<?>> maybeClass = getAppClass();
Class<?> aClass = maybeClass.get();
Optional<Method> maybeMethod = findMethod(aClass, methodName, int[].class);
assertTrue(maybeMethod.isPresent(), methodName + " should be present in " + aClass.getCanonicalName());
final Method method = maybeMethod.get();
assertTrue(isPrivate(method), methodName + " should be private");
assertEquals(int.class, method.getReturnType(), methodName + " should return type should be 'int'");
}
I am making use of ReflectionUtils class
I wanted to know if there is a way to test that privateMethod
contains a variable called sum
and its type is int
?
Solution
As Eliot Frisch mentioned in the comments, you cannot, since variable names aren't represented in the byte code.
Moreover, you really shouldn't. You could change the variable's name and have a method which exactly the same functionality:
private int privateMethod(int[] numbers) {
var notSum = 0;
for (int number : numbers) {
notSum += number;
}
return notSum;
}
so why would you want your unit test to break from such a refactoring?
Answered By - Mureinik
Answer Checked By - Senaida (JavaFixing Volunteer)