Test output contents to file

时间:2015-12-10 01:05:01

标签: java unit-testing testing junit

I have a function write(). This function will output text to a text file and I want to test the output.

public class Item {

    String itemOne, itemTwo;

    public Item(String itemOne, String itemTwo) {
        this.itemOne = itemOne;
        this.itemTwo = itemTwo;
    }

    public String getItemOne() {
        return itemOne;
    }

    public String getItemTwo() {
        return itemTwo;
    }

    public static void main(String args[]) {
        File outFile = new File("out.txt");
        ArrayList<Item> item = new ArrayList<Item>();
        FileWriter fw = new FileWriter(outFile.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);

        item.add(new Item("Item 1", "Item 2"));
        item.add(new Item("Item 3", "Item 4"));
        write(bw,item);
    }

    public static void write(BufferedWriter bw,ArrayList<Item> item) throws IOException {
        for(int i = 0; i < item.size(); i++) {

            bw.write(item.get(i).getItemOne() + "," + item.get(i).getItemTwo());
            bw.newLine();

        }
        bw.close();
    }
}

I tried writing the test case but I am not sure how should I write

public class TestCase {
    TestCase testCase = new TestCase();
    @Test
    public void testOutputToFile() throws IOException {
        File outFile = new File("out.txt");
        ArrayList<Item> itemList = new ArrayList<Item>();
        FileWriter fw = new FileWriter(outFile.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);

        itemList.add(new Item("Item1","Item2")); 
        itemList.add(new Item("Item3","Item4")); 

        assertEquals(new Item("Item1","Item2")), bw); 
        assertEquals(new Item("Item3","Item4")), bw); 
    }
}

Please help. I got StackoverflowError after I run my TestCase.java

1 个答案:

答案 0 :(得分:3)

It really depends on what behaviour you are trying to test. If you are trying to verify the output to the BufferedWriter, I would suggest wrapping it around a StringWriter and then verifying its contents like so:

import static org.junit.Assert.assertEquals;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;

public class ItemTest {
    @Test
    public void testOutputToFile() throws IOException {
        List<Item> itemList = new ArrayList<Item>();
        StringWriter sw = new StringWriter();
        BufferedWriter bw = new BufferedWriter(sw);

        itemList.add(new Item("Item1","Item2")); 
        itemList.add(new Item("Item3","Item4")); 

        Item.write(bw, itemList);

        String string = sw.toString();
        String expectedString = "Item1,Item2" + System.lineSeparator() + "Item3,Item4" + System.lineSeparator();

        assertEquals(expectedString, string);
    }
}