如何测试私有方法是否有一个带有名称和类型的字段?
How do I test if a private method has a field with a name and a type?
这是我要测试的私有方法:
private int privateMethod(int[] numbers) {
var sum = 0;
for (int number : numbers) {
sum += number;
}
return sum;
}
我在 Java 11.
下面是我使用 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'");
}
我正在使用 ReflectionUtils class
我想知道是否有一种方法可以测试 privateMethod
包含一个名为 sum
的变量并且它的类型是 int
?
正如 Eliot Frisch 在评论中提到的那样,您不能这样做,因为字节码中没有表示变量名。
而且,你真的不应该。您可以更改变量的名称并使用一种方法完全具有相同的功能:
private int privateMethod(int[] numbers) {
var notSum = 0;
for (int number : numbers) {
notSum += number;
}
return notSum;
}
那么,为什么您希望您的单元测试打破这样的重构?
这是我要测试的私有方法:
private int privateMethod(int[] numbers) {
var sum = 0;
for (int number : numbers) {
sum += number;
}
return sum;
}
我在 Java 11.
下面是我使用 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'");
}
我正在使用 ReflectionUtils class
我想知道是否有一种方法可以测试 privateMethod
包含一个名为 sum
的变量并且它的类型是 int
?
正如 Eliot Frisch 在评论中提到的那样,您不能这样做,因为字节码中没有表示变量名。
而且,你真的不应该。您可以更改变量的名称并使用一种方法完全具有相同的功能:
private int privateMethod(int[] numbers) {
var notSum = 0;
for (int number : numbers) {
notSum += number;
}
return notSum;
}
那么,为什么您希望您的单元测试打破这样的重构?