2016-03-09 45 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。只是它。 –