簡體   English   中英

Java:如何測試保存方法?

[英]Java : How can I test save method?

我有以下保存方法,但是我不知道如何驗證該方法是否正常工作。 如何在測試課程中進行驗證?

 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方法構造的。

像這樣從您的方法中刪除FileWriter

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

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

   pw.flush();
}

在您的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);
...

對於測試,您可以考慮使用諸如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。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM