|
| 1 | +package httpserver.responder; |
| 2 | + |
| 3 | +import httpserver.AppConfig; |
| 4 | +import httpserver.Request; |
| 5 | +import httpserver.file.FileOperator; |
| 6 | +import httpserver.file.PathExaminer; |
| 7 | +import httpserver.header.Header; |
| 8 | +import httpserver.response.Response; |
| 9 | +import org.junit.Test; |
| 10 | + |
| 11 | +import java.io.IOException; |
| 12 | +import java.nio.file.Path; |
| 13 | + |
| 14 | +import static org.junit.Assert.*; |
| 15 | +import static org.mockito.Mockito.*; |
| 16 | + |
| 17 | +public class FormGetResponderTest { |
| 18 | + private final FormGetResponder formGetResponder; |
| 19 | + private final PathExaminer pathExaminerMock; |
| 20 | + private final FileOperator fileOperatorMock; |
| 21 | + private final Path rootMock; |
| 22 | + private final Path fullPathMock; |
| 23 | + private final byte[] fileContentsMock; |
| 24 | + private final AppConfig appConfigMock; |
| 25 | + private final String pathString; |
| 26 | + |
| 27 | + public FormGetResponderTest() throws IOException { |
| 28 | + rootMock = mock(Path.class); |
| 29 | + pathString = "/form"; |
| 30 | + fileContentsMock = "file contents mock".getBytes(); |
| 31 | + fullPathMock = mock(Path.class); |
| 32 | + pathExaminerMock = mock(PathExaminer.class); |
| 33 | + when(pathExaminerMock.getFullPath(rootMock, pathString)).thenReturn(fullPathMock); |
| 34 | + fileOperatorMock = mock(FileOperator.class); |
| 35 | + when(fileOperatorMock.readContents(fullPathMock)).thenReturn(fileContentsMock); |
| 36 | + appConfigMock = mock(AppConfig.class); |
| 37 | + when(appConfigMock.getRoot()).thenReturn(rootMock); |
| 38 | + formGetResponder = new FormGetResponder(pathExaminerMock, fileOperatorMock); |
| 39 | + } |
| 40 | + |
| 41 | + @Test |
| 42 | + public void returnsOkResponse() throws Exception { |
| 43 | + when(pathExaminerMock.pathExists(any())).thenReturn(true); |
| 44 | + Request request = new Request("GET", pathString, new Header[0], ""); |
| 45 | + |
| 46 | + Response response = formGetResponder.respond(appConfigMock, request); |
| 47 | + |
| 48 | + verify(pathExaminerMock).pathExists(fullPathMock); |
| 49 | + assertEquals(200, response.getStatusCode()); |
| 50 | + assertEquals("file contents mock", new String(response.getPayload())); |
| 51 | + } |
| 52 | + |
| 53 | + @Test |
| 54 | + public void createsFormFileIfDoesntExist() throws Exception { |
| 55 | + when(pathExaminerMock.pathExists(any())).thenReturn(false); |
| 56 | + Request request = new Request("GET", pathString, new Header[0], ""); |
| 57 | + |
| 58 | + Response response = formGetResponder.respond(appConfigMock, request); |
| 59 | + |
| 60 | + verify(fileOperatorMock).createFileAtPath(fullPathMock); |
| 61 | + } |
| 62 | + |
| 63 | + @Test |
| 64 | + public void formIsAllowed() throws Exception { |
| 65 | + assertTrue(formGetResponder.allowed("/form")); |
| 66 | + assertFalse(formGetResponder.allowed("/other")); |
| 67 | + } |
| 68 | +} |
0 commit comments