我想创建用于将文件值读入JUnit测试的模拟测试。
我是这段代码来阅读文本代码。
BufferedReader cpuReader = new BufferedReader(new InputStreamReader(new FileInputStream("/opt/test")));
为了创建JUnit测试,我需要添加一些我需要保存到Java缓冲区中的虚拟数据。仅举例(这是完全错误的)我想这样做:
BufferedReader cpuReader = new BufferedReader():
cpuReader.addText("Some text");
// process further this data
我可以告诉我在初始化Object BufferedReader()时将一些文本添加到变量cpuReader中的正确方法是什么?
答案 0 :(得分:3)
您可以使用PushbackReader将文本添加回流中:
String textToAdd = "Some text";
PushbackReader cpuReader = new PushbackReader(
new BufferedReader(new InputStreamReader(new FileInputStream("/opt/test"))),
textToAdd.length());
cpuReader.unread(textToAdd.toCharArray());
答案 1 :(得分:2)
你应该这样做:
String str = "The string you want for your output";
BuffereReader r = new BufferedReader(new StringReader(str))
尽量不要模拟文件,有许多缺点。
答案 2 :(得分:1)
以下是使用StringReader
:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
public class SimpleTest {
public static void main(String[] args) {
// Create a BufferedReader based on a string
String s = "This is my input\nIt has two lines\n";
StringReader strReader = new StringReader(s);
BufferedReader cpuReader = new BufferedReader(strReader);
// Use the BufferedReader, regardless of its source.
String line;
try {
while ((line = cpuReader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
请注意,一旦您创建了cupReader
,就可以像以前一样使用它,无论它是基于StringReader
。
答案 3 :(得分:1)
另一种方法是将BufferedReader与PipedReader挂钩,如下所示:
PipedReader pipeR = new PipedReader();
BufferedReader br = new BufferedReader(pipeR);
然后将PipedReader与PipedWriter连接起来,如:
// create a new Piped writer and reader
PipedWriter writer = new PipedWriter();
// connect the reader and the writer
pipeR.connect(writer);
现在(并以动态方式),无论您使用编写器写入方法编写的数据,还可以通过BufferedReader读取它