首页 > 解决方案 > 在 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 但不想打印任何内容或执行任何额外的计算。但在实际程序执行过程中,对程序的功能没有影响。我可以知道是否有任何方法可以做到吗?

谢谢!

标签: javaunit-testingtestingjunit

解决方案


对于您的具体情况:您可以使用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...
}

我可以进一步解释它如何发生的,但我想这对你的回答来说已经足够了。如果您好奇,可以查看测试的运行时执行情况,以检查模拟对象的真实类型。


推荐阅读