【问题标题】:In Java how to display function parameters when the function is called at much higher level? [duplicate]在Java中如何在更高级别调用函数时显示函数参数? [复制]
【发布时间】:2021-04-06 13:37:39
【问题描述】:

为了练习算法问题,我将我的 Java 代码设置为: 问题类.java

public static void main(String[] args) {
        Solution solution = new ProblemClass().new Solution();
        Utils.isEqual(solution.function("abc"), "def");
}
public class {
    public Solution {
        public String function(String s) {}
    }
}

Utils.isEqual 基本上包装了一个比较,例如:

    public static void isEqual(Object actual, Object expected) {
        if (actual == null && expected == null || actual.equals(expected)) {
            System.out.println("Pass.");
        } else {
            System.out.println("Fail. Expecting: [" + expected + "] Actual result: [" + actual + "]");
        }
    }

当我运行数百个测试用例时,我在命令提示符上看到的只是:

Pass.
Pass.
Pass.
Pass.
...
Fail. Expecting: [false] Actual result: [true]
...

我不知道哪个测试用例失败了。我想知道 what 测试失败了。我愿意接受其他建议。到目前为止,我认为也许有一种方法可以在通过反射之类的方法调用isEqual 时显示传递给function 的参数。我找不到明确的答案。

最后,我想把所有东西都保存在 main() 中,这样我的所有测试和代码都在一个地方,而不是有一个我必须管理的单元测试类。

【问题讨论】:

  • 您可以在断言中包含“消息”。但是使用 JUnit 或 TestNG 之类的测试框架不是更容易吗?
  • 这个问题与“如何在 Java 中获取当前堆栈跟踪?”有何相似之处? ???
  • 我没有投票关闭,但我猜是因为如果您在断言中转储堆栈跟踪,那么您可以准确地跟踪哪个测试失败。但如果可以的话,我仍然建议使用测试框架。

标签: java


【解决方案1】:

您不能访问调用者传递给另一个函数的参数:方法参数仅在方法仍在执行时存储;一旦方法完成执行,保存其参数的存储将被回收并重用于其他目的(例如下一个要执行的函数的参数/局部变量)。

因此,您必须更改代码的结构,以便以某种方式将该值传递给需要它的函数。一个简单的方法是添加一个额外的参数:

public static void assertEquals(String actual, String input, String expected) {
    if (Objects.equals(actual, expected) {
        System.out.println(input + ": pass");
    } else {
        System.out.println(input + ": failed. Expected: " + expected + ", but got " + actual);
    }
}

然后这样称呼它:

assertEquals(solution.function("abc"), "abc", "def");

这可行,但需要两次传递输入。避免这种情况的一种方法是传递解决方案,而不是直接调用其方法:

check(solution, "abc", "def");

在哪里

check(Solution solution, String input, String expected) {
    String actual = solution.function(input);
    if (Objects.equals(expected, actual)) {
        System.out.println(input + ": pass");
    } else {
        System.out.println(input + ": failed. Expected: " + expected + ", but got " + actual);
    }
 }

但是,这仍然需要check 知道要调用哪个方法(function 是我们的示例)。如果您需要 check 使用任意方法,您可以传递方法本身,而不仅仅是定义它的对象:

check(solution::function, "abc", "def");

在哪里

interface TestCase {
    String func(String input);
}

void check(TestCase test, String input, String expectedOutput) {
    String output = test.func(input);
    // compare and print as before
}

综上所述,在专业代码中,您可能会使用像 junit 这样的测试框架,而不是重新发明轮子。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-14
    • 2014-11-16
    • 1970-01-01
    • 1970-01-01
    • 2016-05-24
    相关资源
    最近更新 更多