为了练习算法问题,我设置了如下 Java 代码: ProblemClass.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]
...
我不知道哪个测试用例失败了。我想要知道什么测试失败了。我愿意接受其他建议。到目前为止,我想也许有一种方法可以显示传入 function
的参数。调用isEqual
时通过诸如反射之类的东西。我找不到明确的答案。
最后,我想将所有内容保留在 main() 中,以便我的所有测试和代码都位于一个位置,而不是拥有一个我必须管理的单元测试类。
最佳答案
您无法访问调用者传递给另一个函数的参数:方法参数仅在方法仍在执行时存储;一旦方法完成执行,保存其参数的存储将被回收并重新用于其他目的(例如下一个要执行的函数的参数/局部变量)。
因此,您必须更改代码的结构,以便该值以某种方式传递给需要它的函数。一个简单的方法是添加一个附加参数:
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 这样的测试框架,而不是重新发明轮子。
关于java - 在Java中,当在更高级别调用函数时如何显示函数参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65500363/