Java:我如何测试save方法?

时间:2016-03-09 12:10:17

标签: java

我有以下保存方法,但我不知道如何验证方法是否正常工作。如何在Test Class中验证它?

 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);
   }
 }

抱歉,内容不是String,而是List。但是没有必要制作测试类吗?因为它是由经过测试的java方法构建的。

2 个答案:

答案 0 :(得分:1)

从您这样的方法中删除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);
...

答案 1 :(得分:1)

对于测试,您可以考虑使用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。