如何测试 类 的方法,其中该方法也在构造函数中调用? (联合)

How do I test methods of classes in which the method is also called in the constructor? (JUnit)

我是测试驱动开发 (TDD) 的初学者。很多时候,我遇到了一些不合适的做事方式:

举个例子,一个 class 和一个名为 loadStuff() 的方法,如果加载或不加载东西,它将 return truefalse。此方法在 class.

的构造函数中调用
public class Main {
    public static void main(String[] args) {
        new Main();
    }

    public Main() {
        if (loadStuff())
            System.out.println("Stuff was loaded from constructor");
        else
            System.out.println("Stuff was not loaded from constructor");
    }

    boolean loadStuff() {
        boolean stuffWasLoaded = true;
        //...
        return stuffWasLoaded;
    }
}

我想使用 JUnit 测试此 loadStuff() 方法。令我困扰的是,在我实际测试它之前,我正在尝试测试的方法在 class 的构造函数中被调用:

import org.junit.Test;

import static org.junit.Assert.*;

public class MainTest {

    @Test
    public void testLoadStuff() throws Exception {
        Main main = new Main();

        assertTrue("Stuff was not loaded from test.", main.loadStuff());
    }
}

测试通过,这是输出:

Stuff was loaded from constructor

Process finished with exit code 0

我觉得我的做法是错误的,但不确定是否有更好的方法。

测试 class 的方法的正确方法是什么,该方法也在 class 的构造函数中调用?

这是全新的代码吗?就好像这样使用 TDD 你所描述的情况不应该出现。

循环为:

  1. 写一个失败的(但编译测试)
  2. 编写最少的代码量以通过测试
  3. 重构(整理并删除重复项)

在此之后,构造函数中不可能有未经测试的方法调用。

您想测试 class 的行为,而不是单个方法本身。确定您想要的行为,编写测试预期输出的测试用例,然后编写代码。