I got below code in a method which I want to test
File f = map.get("key1")
BuffereReader r = new BufferedReader(new FileReader(f));
String line=null;
do {
line=r.readLine();
} while(r!=null);
I want to mock this operation so that I can pass the content of the file from the JUnit test case. I have done below:
Map fles = Mockito.mock(ConcurrentHashMap.class);
File file = Mockito.mock(File.class);
Mockito.when(files.get("key1")).thenReturn(file);
FileReader fileReader = Mockito.mock(FileReader.class);
BufferedReader bufferedReader = Mockito.mock(BufferedReader.class);
try {
PowerMockito.whenNew(FileReader.class).withArguments(file).thenReturn(fileReader);
PowerMockito.whenNew(BufferedReader.class).withArguments(fileReader).thenReturn(bufferedReader);
PowerMockito.when(bufferedReader.readLine()).thenReturn("line1")
.thenReturn("line2").thenReturn("line3");
} catch (Exception e) {
Assert.fail();
}
So basically I need to pass "line1", "line2" and "line3" as lines from the file which are read by the mocked BufferedReader.
However upon doing that, it failes as NullPointerException when trying to instantiate new FileReader(f) part.
So is it because I can't mock a BufferedReader or the approach is wrong?
Thanks
You could extract a method for doing the actual reading and then test that instead. That would mean you only have to mock a single reader. For example, your code would be something like this:
public void aMethod(){
File f = map.get("key1")
BuffereReader r = new BufferedReader(new FileReader(f));
readStuff(r);
}
public void readStuff(BufferedReader r){
String line=null;
do {
line=r.readLine();
} while(r!=null);
}
then your test code would be more like the following:
BufferedReader bufferedReader = Mockito.mock(BufferedReader.class);
Mockito.when(bufferedReader.readLine()).thenReturn("line1", "line2", "line3");
objUnderTest.readStuff(bufferedReader);
//verify result
You can try PowerMock annotations. Check this : https://code.google.com/p/powermock/wiki/MockConstructor
Related
I want to pars GOv2 collection format and I want to use TrecGov2Parser. I find its code in this page. The input file is test file and it contains just one document of GOV2 collection.
This is my code:
public static void writeHTMLText()
{
try
{
FileWriter fw1= new FileWriter(new File("/home/fl/Desktop/GOV_Text/GOV/00.txt"));
BufferedWriter bw1 = new BufferedWriter(fw1);
FileReader fileReader = new FileReader(new File("/home/fl/Desktop/GOV/00"));
BufferedReader br = new BufferedReader(fileReader);
String docs="";
String line;
while((line=br.readLine())!= null )
docs= docs+line+"\n";
DocData docData = new DocData();
DocData result = new TrecGov2Parser().parse(docData,"result00",new TrecContentSource(),new StringBuilder(docs),TrecDocParser.ParsePathType.GOV2);
bw1.write(result.getBody());
br.close();
bw1.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
I got this error.
java.lang.NullPointerException
at org.apache.lucene.benchmark.byTask.feeds.TrecGov2Parser.parse(TrecGov2Parser.java:56)
at LuceneParser.parserInput.writeHTMLText(parserInput.java:63)
I add *lucene-core-3.4.0.jar* and *lucene-benchmark-3.4.0.jar* to my project buildpath.
What do I need to do?
There is no private, protected or public keyword at getHtmlParser(). This means you can call this method only from inside the same package (default/package visibility). The method is intended not to be used by others.
I would like to create mock test for reading file values into JUnit test.
I'm this code to read text code.
BufferedReader cpuReader = new BufferedReader(new InputStreamReader(new FileInputStream("/opt/test")));
In order to create JUnit test I need to add some dummy data which I need to keep into Java buffer. Just for example (it's completely wrong) I want to do this:
BufferedReader cpuReader = new BufferedReader():
cpuReader.addText("Some text");
// process further this data
Can you show me what is the correct way to add some text into the variable cpuReader when I initialize the Object BufferedReader()?
You should do something like this:
String str = "The string you want for your output";
BuffereReader r = new BufferedReader(new StringReader(str))
Try not to mock files, there are many disadvantages.
You can use a PushbackReader to add text back into the stream:
String textToAdd = "Some text";
PushbackReader cpuReader = new PushbackReader(
new BufferedReader(new InputStreamReader(new FileInputStream("/opt/test"))),
textToAdd.length());
cpuReader.unread(textToAdd.toCharArray());
Here is an example of using a 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();
}
}
}
Note that once you have created the cupReader, you use it just like you did before, regardless of the fact that it's based on a StringReader.
Another way to do it is to hook up a BufferedReader with a PipedReader like this:
PipedReader pipeR = new PipedReader();
BufferedReader br = new BufferedReader(pipeR);
And then to connect the PipedReader with a PipedWriter like in:
// create a new Piped writer and reader
PipedWriter writer = new PipedWriter();
// connect the reader and the writer
pipeR.connect(writer);
Now (and in a dynamic fashion), whatever data you write using the writer write method, you can also read it via your BufferedReader
I generate a XML like this. It works fine. But I want to print it out in Eliscps:
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;
public class PersonConstructor {
String info="";
String path="c://myfile/myperson";
// here is my xml object
Person person = new Person();
person.setFirstName("fname");
person.setLastName("lname");
person.setTel("111-111-1111");
person.setAddress("1000 main st.");
//Serializer my object to file.
Serializer serializer = new Persister();
File file = new File(path);
serializer.write(person, file);
//now I want to print out my xml file.I don't know how to do it.
info = file.toString();
System.out.println(info);
}
Should I use output stream?
Use a buffered reader. Just make sure to either add the IOException to your method signature or surround with try/catch block.
BufferedReader in = new BufferedReader(new FileReader(file));
String line = in.readLine();
while(line != null)
{
System.out.println(line);
line = in.readLine();
}
in.close();
I'm writing a test case where I'm trying to use mockito to avoid entering text through console. But on running the test case, it waits for something to be entered in console (which is again something I'm unable to do) instead of getting it from mockito. Would appreciate if someone can help. The test code looks like this:
SongsNameUpdater songsNameUpdater = new SongsNameUpdater();
bufferedReader = mock(BufferedReader.class);
when(bufferedReader.readLine()).thenReturn("test Path");
songsNameUpdater.updateSongNames();
The main code is:
public class SongsNameUpdater {
public void updateSongNames() throws IOException {
bufferedReader = new BufferedReader(new InputStreamReader(System.in));
String path = bufferedReader.readLine();
System.out.println(path);
}
}
You have to pass your BufferedReader mock e.g. like updateSongNames(bufferedReader) and not instantiating it within the method
first time post here.
I am in the process of writing a Java program that takes an input text file, reads the contents, and then prints them to the screen and also creates an output file with the contents. I have set up the necessary writers, but when I try to use BufferedReader readername = new BufferedReader(new FileReader(inFile)); it gives me the error in the title.
Any ideas what's causing it?
Here's the code.
public class FileReader
{
public static void main(String[] args) throws IOException
{
try
{
File inFile = new File("inputText.txt");
BufferedReader reader = new BufferedReader(new FileReader(inFile));
String line = null;
BufferedWriter writer = new BufferedWriter(new FileWriter("Contents.txt"));
while ((line=reader.readLine()) != null)
{
writer.write(line);
System.out.println("File 'Contents.txt' successfully written");
System.out.println(line);
}
}
catch (IOException e)
{
System.out.println(e);
}
}
}
Use the fully qualified class name java.io.FileReader since you have a class already called FileReader when calling a BufferedReader, like so:
BufferedReader reader = new BufferedReader(new java.io.FileReader(inFile));
Without fully qualifying your FileReader (or specifying imports), the compiler will use your declared FileReader.
The problem here is that your class name is FileReader and you want to use java.io.FileReader hence compiler is confused and instead of java.io.FileReader it assumes it be your class. Basically your ClassName shadows the name from java.io package.
Rename your class to something else like MyFileReader or use fully qualified named java.io.FileReader