gpt4 book ai didi

java - 测试输出内容到文件

转载 作者:行者123 更新时间:2023-11-28 21:04:39 26 4
gpt4 key购买 nike

我有一个函数 write()。此函数会将文本输出到文本文件,我想测试输出。

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

我试过写测试用例,但我不知道该怎么写

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

请帮忙。运行 TestCase.java 后出现 StackoverflowError

最佳答案

这实际上取决于您要测试的行为。如果您尝试验证 BufferedWriter 的输出,我建议将其包装在 StringWriter 中,然后像这样验证其内容:

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

关于java - 测试输出内容到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34191999/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com