Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test write to file in Java?

I'm beginner, and keep yourself in hands. I have some easy program, and I need do junit test for write method. I have some collection in input. How I can do this? This my code:

// write to file
public void write(String fileName, 
        List<FigureGeneral> figuresList) {
    try {
        PrintWriter out = new PrintWriter(
                new File(fileName).getAbsoluteFile());
        try {
            for (int i = 0; i < figuresList.size(); i++) {
                out.println(figuresList.get(i).toString());
            }
        } finally {
            out.close();
        }
    } catch (IOException e) {
        System.out.println("Cannot write to file!");
    }
}

And I want to know, coz after this I read from file, can we join both tests(write/read) or better do this individually(coz if our test fall we don't know where is problem - in read or write)? How should make this correctly at junit(with prepare to test, and test itself)? Better show on example, this way better to understand.

Thanks, Nazar.

like image 511
catch23 Avatar asked Jan 12 '13 15:01

catch23


People also ask

How do I run a test file in Java?

Create Test Runner Class It imports the JUnitCore class and uses the runClasses() method that takes the test class name as its parameter. Compile the Test case and Test Runner classes using javac. Now run the Test Runner, which will run the test case defined in the provided Test Case class. Verify the output.


1 Answers

You probably don't need mocks at all. Try using StringWriter in your tests.

// write to file
public void write(String fileName, List<FigureGeneral> figuresList) {
  try {
    Writer out = new FileWriter(new File(fileName).getAbsoluteFile());
    write(out, figuresList);
  } catch (IOException e) {
    System.out.println("Cannot write to file!");
  }
}

@VisibleForTesting void write(Writer writer, List<FigureGeneral> figuresList) {
  PrintWriter out = new PrintWriter(writer);
  try {
    for (int i = 0; i < figuresList.size(); i++) {
      out.println(figuresList.get(i).toString());
    }
  } finally {
    out.close();
  }
}

@Test public void testWrite() {
  List<FigureGeneral> list = Lists.newArrayList();
  list.add(...); // A
  list.add(...); // B
  list.add(...); // C
  StringWriter stringWriter = new StringWriter();
  write(stringWriter, list);
  assertEquals("A.\nB.\nC.\n", stringWriter.toString()); 
}
like image 55
Jeff Bowman Avatar answered Sep 25 '22 17:09

Jeff Bowman