|
| 1 | +package org.juv25d.http; |
| 2 | + |
| 3 | +import org.junit.jupiter.api.DisplayName; |
| 4 | +import org.junit.jupiter.api.Test; |
| 5 | + |
| 6 | +import java.io.ByteArrayOutputStream; |
| 7 | +import java.nio.charset.StandardCharsets; |
| 8 | +import java.util.Map; |
| 9 | + |
| 10 | +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; |
| 11 | + |
| 12 | +public class HttpResponseWriterTest { |
| 13 | + |
| 14 | + |
| 15 | + @Test |
| 16 | + @DisplayName("Should write a valid HTTP 200 OK response ") |
| 17 | + void writesValidHttp200Response() throws Exception { |
| 18 | + // Arrange |
| 19 | + HttpResponse response = new HttpResponse( |
| 20 | + 200, |
| 21 | + "OK", |
| 22 | + Map.of("Content-Type", "text/plain"), |
| 23 | + "Hello World".getBytes(StandardCharsets.UTF_8) |
| 24 | + ); |
| 25 | + |
| 26 | + ByteArrayOutputStream out = new ByteArrayOutputStream(); |
| 27 | + |
| 28 | + // Act |
| 29 | + HttpResponseWriter.write(out, response); |
| 30 | + |
| 31 | + // Assert |
| 32 | + String result = out.toString(StandardCharsets.UTF_8); |
| 33 | + |
| 34 | + assertThat(result).startsWith("HTTP/1.1 200 OK"); |
| 35 | + assertThat(result).contains("Content-Type: text/plain"); |
| 36 | + assertThat(result).contains("Content-Length: 11"); |
| 37 | + assertThat(result).endsWith("Hello World"); |
| 38 | + } |
| 39 | + |
| 40 | + @Test |
| 41 | + @DisplayName("Should write a valid HTTP 404 Not Found Response") |
| 42 | + void writes404NotFoundResponse() throws Exception { |
| 43 | + HttpResponse response = new HttpResponse( |
| 44 | + 404, |
| 45 | + "Not Found", |
| 46 | + Map.of("Content-Type", "text/plain"), |
| 47 | + "Not found".getBytes(StandardCharsets.UTF_8) |
| 48 | + ); |
| 49 | + |
| 50 | + ByteArrayOutputStream out = new ByteArrayOutputStream(); |
| 51 | + |
| 52 | + HttpResponseWriter.write(out, response); |
| 53 | + |
| 54 | + String result = out.toString(StandardCharsets.UTF_8); |
| 55 | + |
| 56 | + assertThat(result).startsWith("HTTP/1.1 404 Not Found"); |
| 57 | + } |
| 58 | + |
| 59 | +} |
0 commit comments