Skip to content

Commit 3e750d3

Browse files
committed
Update Logger to throw Runtime Exception when created if it can't create the logfile
1 parent f19f849 commit 3e750d3

File tree

2 files changed

+13
-3
lines changed

2 files changed

+13
-3
lines changed

src/main/java/httpserver/Logger.java

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ public class Logger {
1111
private final Path logPath;
1212
private final PrintStream errorStream;
1313

14-
public Logger(Path logPath, FileOperator fileOperator, PrintStream errorStream) throws IOException {
14+
public Logger(Path logPath, FileOperator fileOperator, PrintStream errorStream) {
1515
this.fileOperator = fileOperator;
1616
this.logPath = logPath;
1717
this.errorStream = errorStream;
@@ -30,7 +30,9 @@ public void log(String logString) {
3030
private void createFileIfDoesntExist(Path path) {
3131
try {
3232
fileOperator.createFileAtPath(path);
33-
} catch (IOException e) { }
33+
} catch (IOException e) {
34+
throw new RuntimeException(e);
35+
}
3436
}
3537

3638
public byte[] readLog() throws IOException {

src/test/java/httpserver/LoggerTest.java

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,11 +21,13 @@ public class LoggerTest {
2121
private final Path logPath;
2222
private final Logger logger;
2323
private final PrintStream printStreamMock;
24+
private final FileOperator fileOperatorMock;
2425

2526
public LoggerTest() throws IOException {
2627
logPath = Paths.get(tempDir().toString(), "logs");
2728
printStreamMock = mock(PrintStream.class);
2829
logger = new Logger(logPath, new FileOperator(), printStreamMock);
30+
fileOperatorMock = mock(FileOperator.class);
2931
}
3032

3133
@Test
@@ -50,12 +52,18 @@ public void writesToLogAndReadsFromLog() throws Exception {
5052

5153
@Test
5254
public void printsErrorToStdErrIfCantWriteToLog() throws Exception {
53-
FileOperator fileOperatorMock = mock(FileOperator.class);
5455
doThrow(new IOException()).when(fileOperatorMock).appendToFile(any(), any());
5556
Logger logger = new Logger(logPath, fileOperatorMock, printStreamMock);
5657

5758
logger.log("");
5859

5960
verify(printStreamMock).print(any(Exception.class));
6061
}
62+
63+
@Test(expected = RuntimeException.class)
64+
public void throwsRuntimeExceptionIfCantCreateLogFile() throws Exception {
65+
doThrow(new IOException()).when(fileOperatorMock).createFileAtPath(any());
66+
67+
Logger logger = new Logger(logPath, fileOperatorMock, printStreamMock);
68+
}
6169
}

0 commit comments

Comments
 (0)