2016-03-09 49 views
-1

我有以下保存方法,但我不知道如何驗證該方法是否正常工作。我如何在測試類中驗證它?Java:我如何測試保存方法?

static void saveFile(List<String> contents, String path){ 

    File file = new File(path); 
    PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file))); 

    for(String data : contents){ 
     pw.println(data); 
    } 
} 

對不起,內容不是字符串,而是列表。但是,有沒有必要做測試課?因爲它是通過測試的java方法構造的。

+0

創建另一個稱爲loadFile的方法並讀取寫入的數據並驗證內容在兩種情況下都是相同的 – Pooya

+3

爲什麼要測試Java Standard類?你應該測試你的方法沒有邏輯。 – Jens

+0

您未在方法中關閉PrintWriter,因此它不會將所有行寫入文件。另外,你意識到已經有一個標準的方法'Files.write'來做同樣的事情,不是嗎? –

回答

1

從你的方法是這樣

static void saveFile(List<String> contents, Writer writer){ 
    PrintWriter pw = new PrintWriter(new BufferedWriter(writer)); 

    for(String data : contents){ 
     pw.println(data); 
    } 

    pw.flush(); 
} 

刪除FileWriter在你JUnit測試方法使用StringWriter檢查您節省邏輯

@Test 
void testWriter() { 
    StringWriter writer = new StringWriter(); 
    saveFile(Arrays.asList("test content", "test content2"), writer); 
    assertEquals("test content\ntest content2\n", writer.toString()); 
} 

,並在您的實際代碼

... 
Writer writer = new FileWriter(new File(path)); 
saveFile(Arrays.asList("real content", "real content2"), writer); 
... 
+2

以及它如何測試函數的正確性? – Pooya

+0

@Pooya看到我的回答更新 –

+2

writer.toString()不會返回寫的內容 – Pooya

1

對於測試,你可以考慮一個這樣的測試框架s的jUnit並編寫你的測試用例。在特定情況下,可以按如下方式寫的東西:

public class TestCase { 

    @Test 
    public void test() throws IOException { 
     String contents = "the your content"; 
     String path = "the your path"; 

     // call teh metod 
     saveFile(contents, path); 

     // tacke a reference to the file 
     File file = new File(path); 

     // I assert that the file is not empty 
     Assert.assertTrue(file.length() > 0); 

     // I assert that the file content is the same of the contents variable 
     Assert.assertSame(Files.readLines(file, Charset.defaultCharset()).stream().reduce("", (s , s2) -> s+s2),contents); 
    } 


    static void saveFile(String contents, String path) throws IOException { 

     File file = new File(path); 
     PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file))); 

     pw.println(contents); 
    } 
} 

這樣,你有一個框架來檢查你的代碼工作像您期望的。如果這還不夠,你應該研究一個模擬框架,比如Mockito。

+0

您不需要測試真正的文件寫入,但需要編寫邏輯。 –

+0

我同意你的意見Andriy,我的回答是作爲技術支持,換句話說,如果你想在一個方法上執行測試用例,因爲在這個問題中可能是一個不錯的選擇,選擇一個測試框架並在我的answare顯示一個使用方法jUnit api。只是它。 –