Use of the Set Up and Tear Down methods in JUnits

JUnit  follows  a  very  specific  sequence  of  events  when  invoking  tests.  First,  it  constructs a newinstance of the test case for each test method. Thus, if you have five test methods, JUnit constructs five instances of your test case. For this reason, instance variables cannot be used to share state between test methods. After constructing all of the test case objects, JUnit follows these steps for each test method: 
  •   Calls the test case’s setUp() method 
  •   Calls the test method 
  •   Calls the test case’s tearDown() method.
This process repeats for each of the test methods in the test case.


Sample Code :

import java.io.IOException; 
             import junit.framework.TestCase; 
             public class HtmlDocumentTest extends DocumentTestCase 
             { 
                  public HtmlDocumentTest (String name) { 
                       super(name); 
                  } 
               HtmlDocument doc; 
               public void setUp() throws IOException { 
                       doc = new HtmlDocument(getFile("test.html")); 
                  } 

                  public void testDoc() { 
          assertEquals("Title", "Test Title", doc.getTitle()); 
          assertEquals("Body", "This is some test", doc.getBodyText()); 
                  } 
                  public void tearDown() { 
                       doc = null; 
                  } 
             } 


Enter your email address to get our daily JOBS & INTERVIEW FAQ's Straight to your Inbox.

Make sure to activate your subscription by clicking on the activation link sent to your email