[英]How can I control whether JUnit creates an instance of the class whose behaviour is being tested?
I have noticed that JUnit implicitly creates an instance of my test class.我注意到 JUnit 隐式地创建了我的测试类的一个实例。 I have added my own call to the constructor and this does not prevent the creation of the instance by JUnit;
我已经向构造函数添加了自己的调用,这不会阻止 JUnit 创建实例; the net result is two instances are created, as shown by the console output below.
最终结果是创建了两个实例,如下面的控制台输出所示。 I find this puzzling.
我觉得这很令人费解。 Why is this taking place, and how can I control/prevent the creation of the instance by JUnit?
为什么会发生这种情况,我如何控制/阻止 JUnit 创建实例? A google search "junit implicit object creation" reveals nothing, but I was able to see where the constructor is invoked by debugging the test.
谷歌搜索“junit 隐式对象创建”没有显示任何内容,但我能够通过调试测试看到调用构造函数的位置。 What I don't understand is why this is taking place, when we have a place to do it ourselves, and how to prevent it from taking place.
我不明白的是为什么会发生这种情况,什么时候我们有自己的地方可以做,以及如何防止它发生。 I am using JUnit 4 in eclipse photon.
我在日食光子中使用 JUnit 4。 Thanks.
谢谢。
public class MainTest extends Main {
static Main m;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
System.out.println("setUpBeforeClass");
m = new Main();
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
System.out.println("tearDownAfterClass");
}
@Before
public void setUp() throws Exception {
System.out.println("setup");
}
@After
public void tearDown() throws Exception {
System.out.println("tearDown");
}
@Test
public void testAdd() {
assertEquals(8,m.add(3,5));
}
}
Console output:控制台输出:
setUpBeforeClass
Main()
Main()
setup
tearDown
tearDownAfterClass
您的测试用例扩展了 Main 类,这意味着在创建 MainTest 类和显式调用new Main()
调用构造函数,删除extends Main
并且您会很好
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.