Issue
I have noticed that JUnit implicitly creates an instance of my test class. I have added my own call to the constructor and this does not prevent the creation of the instance by 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? A google search "junit implicit object creation" reveals nothing, but I was able to see where the constructor is invoked by debugging the test. 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. 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
Solution
Your testcase extends the class Main which means the constructor is called upon creation of both the MainTest class and the explicit call of new Main()
remove the extends Main
and you'll be good
Answered By - Bloodshaud