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.
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.
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());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With