java - 在 JUnit 测试期间禁用部分 Java 程序
问题描述
我正在用 JUnit 测试我的 Java 程序。该程序包括一些 JavaFX GUI 界面和其他日志记录代码。但是,在测试期间,我不希望对这些进行测试。有没有办法在测试和开发之间切换代码?
描述可以是抽象的,我将使用一个示例:
public class Helloworld {
/**
* @param args the command line arguments
*/
public static int greetingCnt = 0;
public static void main(String[] args) {
Helloworld helloword = new Helloworld();
helloword.greetWorld();
helloword.greetWorld();
helloword.greetWorld();
System.out.println("Greating count: " + greetingCnt);
}
public void greetWorld() {
System.out.println("Hello World!");
++greetingCnt;
//some other computation...
}
}
在此示例中,如果我只想测试正确数量的 greetingCnt 但不想打印任何内容或执行任何额外的计算。但在实际程序执行过程中,对程序的功能没有影响。我可以知道是否有任何方法可以做到吗?
谢谢!
解决方案
对于您的具体情况:您可以使用PowerMock 来模拟System.out
,但老实说,我忽略了它可能产生的全部副作用。
更一般地说:您正在寻找的东西称为Mock object,并且基本上允许 an 的实例Object
什么都不做是运行代码的最低限度。
对于您的情况,模拟System.out
将允许您在System.out.println()
不实际调用这些调用的情况下运行调用。因此,您的代码将像这样执行:
public class Helloworld {
/**
* @param args the command line arguments
*/
public static int greetingCnt = 0;
public static void main(String[] args) {
Helloworld helloword = new Helloworld();
helloword.greetWorld();
helloword.greetWorld();
helloword.greetWorld();
// System.out.println("Greating count: " + greetingCnt);
}
public void greetWorld() {
// System.out.println("Hello World!");
++greetingCnt;
//some other computation...
}
我可以进一步解释它是如何发生的,但我想这对你的回答来说已经足够了。如果您好奇,可以查看测试的运行时执行情况,以检查模拟对象的真实类型。
推荐阅读
- wordpress - 将尾注转换为超链接以导出到 Wordpress
- java - Clickhouse Exception Code 1002 主机端口响应失败
- c++ - 硬币变化:找出重现给定总和的方法的数量
- mule - Dataweave 数据库输出到 CSV 响应
- c# - 为什么EventCallback类型的事件可以
分配 void Foo(DateTime dt) 或 void Foo()? - unity3d - 将 Dicom 图像像素值转换为 Unity 颜色
- javascript - 如何在循环内停止 setTimeout
- javascript - 如何将可选择限制为 1 天或向 dayClick 添加约束?
- javascript - React Native HOC 组件
- javascript - Angular - 如何检查组件标签是否具有特定属性?