我是测试驱动开发(TDD)的初学者。我经常遇到一些感觉不像正确做事方式的事情:
以一个名为 loadStuff()
的方法为例,如果加载或未加载内容,该类将返回 true
或 false
。该方法在类的构造函数中调用。
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 一样,您所描述的情况应该不会出现。
循环是:
- 编写一个失败的(但编译测试)
- 编写最少数量的代码来通过测试
- 重构(整理并删除重复项)
在此之后,不可能在构造函数中调用未经测试的方法。
您想要测试类的行为,而不是单个方法本身。决定您想要什么行为,编写一个测试用例来测试预期的输出,然后编写代码。
关于java - 如何测试在构造函数中也调用该方法的类的方法? (JUnit),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33402536/