在 Junit 测试中,是否可以在 main 方法中测试变量?
我的主要方法是这样的:
package edu.blah.class.project1;
public class Program {
public static void main(String[] args) {
try {
int result = Utility.analyze();
} catch (Exception e) {
System.out.println("Error");
}
}
}
是否可以在 JUnit 类中获取变量结果?是让它成为公共(public)变量的唯一方法吗?谢谢!
最佳答案
In a Junit test, is it possible to test for variables in the main method?
呃……不。除非您有显式调用 main 方法的 JUnit 测试,否则不会在单元测试中调用 main 方法。
此外,这里的变量是result
,它是一个局部变量,无法进入方法来测试某个局部变量。 (Java根本不允许...)
Is it possible to obtain the variable result in a JUnit class?
在此示例中,result
获取调用 Utility.analyze()
的值。没有理由说 JUnit 测试也不能这样做……从而获得相同的值。 (或者至少在这个例子中它可以。)
Is the only way to make it a public variable?
不……见上文。
但是,如果您实际上是在尝试在 main 方法的上下文中测试 result
的值 ,那么您是对的。获取该值的唯一方法是将其公开为 static
变量。不过,它不一定必须是 public static
。 (事实上 ,如果您准备编写一些“讨厌的”反射,您甚至可以让 JUnit 测试提取和测试 private static
字段的值。)
但是,我认为您采取了错误的方法。与其试图弄清楚如何访问静态方法(或任何方法),不如重构代码以使其更易于测试。例如:
package edu.blah.class.project1;
public class Program {
public int run(String args[]) {
return Utility.analyze();
}
public static void main(String[] args) {
try {
new Program().run(args);
} catch (Exception e) {
System.out.println("Error");
}
}
}
通过少量的重构(像这样),您可以更轻松地为所有重要功能编写单元测试。你留下了“问题”,它仍然很难对 main
方法进行单元测试。但是,您已将方法缩减到如此简单,以至于您可以通过目视检查来验证它是否正确:现在不需要单元测试 main
。
关于java - 是否可以从junit测试中获取main方法中的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32602522/