1
2
3
4 package net.sourceforge.pmd.cpd;
5
6 import static org.junit.Assert.assertEquals;
7 import static org.junit.Assert.assertTrue;
8
9 import java.io.BufferedReader;
10 import java.io.File;
11 import java.io.FileReader;
12 import java.io.IOException;
13
14 import org.junit.Test;
15
16
17
18
19 public class FileReporterTest {
20
21 @Test
22 public void testCreation() {
23 new FileReporter((String)null);
24 new FileReporter((File)null);
25 }
26
27 @Test
28 public void testEmptyReport() throws ReportException {
29 File reportFile = new File("report.tmp");
30 FileReporter fileReporter = new FileReporter(reportFile);
31 fileReporter.report("");
32 assertTrue(reportFile.exists());
33 assertEquals(0L, reportFile.length());
34 assertTrue(reportFile.delete());
35 }
36
37 @Test
38 public void testReport() throws ReportException, IOException {
39 String testString = "first line\nsecond line";
40 File reportFile = new File("report.tmp");
41 FileReporter fileReporter = new FileReporter(reportFile);
42
43 fileReporter.report(testString);
44 assertEquals(testString, readFile(reportFile));
45 assertTrue(reportFile.delete());
46 }
47
48 @Test(expected = ReportException.class)
49 public void testInvalidFile() throws ReportException {
50 File reportFile = new File("/invalid_folder/report.tmp");
51 FileReporter fileReporter = new FileReporter(reportFile);
52 fileReporter.report("");
53 }
54
55 private String readFile(File file) throws IOException {
56 BufferedReader reader = null;
57 try {
58 reader = new BufferedReader(new FileReader(file));
59 StringBuffer buffer = new StringBuffer();
60 String line = reader.readLine();
61 while (line != null) {
62 buffer.append(line);
63 line = reader.readLine();
64 if (line != null) {
65 buffer.append('\n');
66 }
67 }
68 return buffer.toString();
69 } finally {
70 if (reader != null)
71 reader.close();
72 }
73 }
74
75 public static junit.framework.Test suite() {
76 return new junit.framework.JUnit4TestAdapter(FileReporterTest.class);
77 }
78 }