|
| 1 | +package com.baeldung.curltojava; |
| 2 | + |
| 3 | +import java.io.File; |
| 4 | +import java.io.IOException; |
| 5 | +import java.io.InputStream; |
| 6 | +import java.net.HttpURLConnection; |
| 7 | +import java.net.URL; |
| 8 | + |
| 9 | +import org.junit.Assert; |
| 10 | +import org.junit.Test; |
| 11 | + |
| 12 | +public class JavaCurlExamplesUnitTest { |
| 13 | + |
| 14 | + |
| 15 | + @Test |
| 16 | + public void givenCommand_whenCalled_thenProduceZeroExitCode() throws IOException { |
| 17 | + String command = "curl --location --request GET \"https://postman-echo.com/get?foo1=bar1&foo2=bar2\""; |
| 18 | + ProcessBuilder processBuilder = new ProcessBuilder(command.replaceAll("\"", "").split(" ")); |
| 19 | + processBuilder.directory(new File("/home/")); |
| 20 | + Process process = processBuilder.start(); |
| 21 | + InputStream inputStream = process.getInputStream(); |
| 22 | + // Consume the inputStream so the process can exit |
| 23 | + JavaCurlExamples.consumeInputStream(inputStream); |
| 24 | + int exitCode = process.exitValue(); |
| 25 | + |
| 26 | + Assert.assertEquals(0, exitCode); |
| 27 | + } |
| 28 | + |
| 29 | + @Test |
| 30 | + public void givenNewCommands_whenCalled_thenCheckIfIsAlive() throws IOException { |
| 31 | + String command = "curl --location --request GET \"https://postman-echo.com/get?foo1=bar1&foo2=bar2\""; |
| 32 | + ProcessBuilder processBuilder = new ProcessBuilder(command.replaceAll("\"", "").split(" ")); |
| 33 | + processBuilder.directory(new File("/home/")); |
| 34 | + Process process = processBuilder.start(); |
| 35 | + |
| 36 | + // Re-use processBuilder |
| 37 | + processBuilder.command(new String[]{"newCommand", "arguments"}); |
| 38 | + |
| 39 | + Assert.assertEquals(true, process.isAlive()); |
| 40 | + } |
| 41 | + |
| 42 | + @Test |
| 43 | + public void whenRequestGet_thenReturnSuccessResponseCode() throws IOException { |
| 44 | + String url = "https://postman-echo.com/get?foo1=bar1&foo2=bar2"; |
| 45 | + URL urlObj = new URL(url); |
| 46 | + HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection(); |
| 47 | + connection.setDoOutput(true); |
| 48 | + connection.setInstanceFollowRedirects(false); |
| 49 | + connection.setRequestMethod("GET"); |
| 50 | + connection.connect(); |
| 51 | + |
| 52 | + Assert.assertEquals(HttpURLConnection.HTTP_OK, connection.getResponseCode()); |
| 53 | + } |
| 54 | + |
| 55 | +} |
0 commit comments