【问题标题】:How do I test if a private method has a field with a name and a type? [duplicate]如何测试私有方法是否具有带有名称和类型的字段? [复制]
【发布时间】:2020-04-18 00:19:20
【问题描述】:

这是我要测试的私有方法:

    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

我想知道是否有办法测试privateMethod 包含一个名为sum 的变量,它的类型是int

【问题讨论】:

  • 我想知道是否有办法测试 privateMethod 包含一个名为 sum 的变量,它的类型是 int? 没有。因为它可以命名为 total 和输入int 并生成完全相同的字节码。
  • 你为什么要尝试测试它?单元测试应该测试方法的效果,在这种情况下意味着测试它是否计算出正确的返回值。 如何计算返回值是方法内部的,而不是你测试的,只有 result 应该被测试。

标签: java junit junit5 java-11


【解决方案1】:

正如 Eliot Frisch 在 cmets 中提到的那样,你不能,因为变量名没有在字节码中表示。

此外,你真的不应该。您可以更改变量的名称并拥有一个完全相同功能相同的方法:

private int privateMethod(int[] numbers) {
    var notSum = 0;
    for (int number : numbers) {
        notSum += number;
    }
    return notSum;
}

那么你为什么要让你的单元测试脱离这样的重构呢?

【讨论】:

  • 您可以使用编译器选项“-parameters”在字节码中保留参数名称。如果依赖该功能是一个好主意还有待讨论。
  • @johanneslink 我不相信。单元测试应该测试函数的功能。我认为穆雷尼克走在正确的轨道上。因此,我建议将其更改为:return Arrays.stream(numbers).sum(); - 现在它根本没有局部变量。我也会将其设为static 方法。它不依赖于任何类成员。
猜你喜欢
  • 2011-09-26
  • 2020-08-03
  • 2018-08-11
  • 2018-02-01
  • 2015-03-14
  • 1970-01-01
  • 1970-01-01
  • 2018-03-10
  • 2019-01-23
相关资源
最近更新 更多