繁体   English   中英

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

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

我是测试驱动开发(TDD)的初学者。 我经常遇到一些不适合做事的事情:

例如,一个类具有一个名为loadStuff()的方法,该类将在加载或不加载内容时返回truefalse 在类的构造函数中调用此方法。

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()方法。 让我困扰的是,我要测试的方法实际上是在类的构造函数中被调用的:

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

我觉得我会以错误的方式进行操作,但是不确定是否有更好的方法。

测试在类的构造函数中也称为类的方法的正确方法是什么?

这是全新的代码吗? 就像使用TDD一样,您的情况不应该出现。

周期为:

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM