2013-03-05 42 views
1
public void createRootElement() throws FileNotFoundException, IOException 
    { 
    Properties prop = new Properties(); 
    prop.load(new FileInputStream("/home/asdf/Desktop/test.properties")); 
     File file = new File(prop.getProperty("filefromroot")); 
     try 
      { 
       // if file doesn't exists, then create it 
       if (!file.exists()) 
        { 
         file.createNewFile(); 
        } 
       FileWriter fw = new FileWriter(file.getAbsoluteFile()); 
       BufferedWriter bw = new BufferedWriter(fw); 
       bw.write("<root>"); //create the root tag for the XML File. 
       bw.close(); 
      } 
     catch(Exception e) 
      { 
      writeLog(e.getMessage(),false); 
      } 
    } 

我是junit testing的新手。我想知道如何編寫測試用例,以及需要考慮的全部內容。如何調用該方法從此測試中調用。從一次測試中調用某個方法時的junit測試

+0

這應該讓你開始:http://junit.sourceforge.net/doc/faq/faq.htm – Aboutblank 2013-03-05 18:31:53

回答

2

JUnit測試用例應該是這樣的:

import static org.junit.Assert.assertTrue; 
import org.junit.Test; 

public class ClassToBeTestedTest { 

    @Test 
    public void test() { 
     ClassToBeTested c = new ClassToBeTested(); 
     c.createRootElement(); 
     assertTrue(c.rootElementExists()); 
    } 

} 

您標記與@Test標註的測試方法,並編寫執行你要測試的代碼。

在這個例子中,我創建了一個類的實例並調用createRootElement方法。

之後,我做了一個斷言來驗證一切是否像我預期的那樣。

有許多事情你可以斷言。閱讀JUnit文檔以獲取更多信息。

一個好的做法是在您實際編寫代碼之前編寫測試。因此,測試將指導您如何編寫更好的代碼。這被稱爲TDD。谷歌爲它。