Add two new modules: <module>core-java-11</module> to project
This commit is contained in:
@@ -0,0 +1,38 @@
|
||||
package com.baeldung;
|
||||
|
||||
import junit.framework.Test;
|
||||
import junit.framework.TestCase;
|
||||
import junit.framework.TestSuite;
|
||||
|
||||
/**
|
||||
* Unit test for simple App.
|
||||
*/
|
||||
public class AppUnitTest
|
||||
extends TestCase
|
||||
{
|
||||
/**
|
||||
* Create the test case
|
||||
*
|
||||
* @param testName name of the test case
|
||||
*/
|
||||
public AppUnitTest(String testName )
|
||||
{
|
||||
super( testName );
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the suite of tests being tested
|
||||
*/
|
||||
public static Test suite()
|
||||
{
|
||||
return new TestSuite( AppUnitTest.class );
|
||||
}
|
||||
|
||||
/**
|
||||
* Rigourous Test :-)
|
||||
*/
|
||||
public void testApp()
|
||||
{
|
||||
assertTrue( true );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.baeldung;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class NewStringAPIUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenRepeatStringTwice_thenGetStringTwice() {
|
||||
String output = "La ".repeat(2) + "Land";
|
||||
|
||||
is(output).equals("La La Land");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenStripString_thenReturnStringWithoutWhitespaces() {
|
||||
is("\n\t hello \u2005".strip()).equals("hello");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenTrimAdvanceString_thenReturnStringWithWhitespaces() {
|
||||
is("\n\t hello \u2005".trim()).equals("hello \u2005");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenBlankString_thenReturnTrue() {
|
||||
assertTrue("\n\t\u2005 ".isBlank());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenMultilineString_thenReturnNonEmptyLineCount() {
|
||||
String multilineStr = "This is\n \n a multiline\n string.";
|
||||
|
||||
long lineCount = multilineStr.lines()
|
||||
.filter(String::isBlank)
|
||||
.count();
|
||||
|
||||
is(lineCount).equals(3L);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.baeldung;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import org.junit.Test;
|
||||
|
||||
public class OuterUnitTest {
|
||||
|
||||
private static final String NEST_HOST_NAME = "com.baeldung.Outer";
|
||||
|
||||
@Test
|
||||
public void whenGetNestHostFromOuter_thenGetNestHost() {
|
||||
is(Outer.class.getNestHost().getName()).equals(NEST_HOST_NAME);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetNestHostFromInner_thenGetNestHost() {
|
||||
is(Outer.Inner.class.getNestHost().getName()).equals(NEST_HOST_NAME);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCheckNestmatesForNestedClasses_thenGetTrue() {
|
||||
is(Outer.Inner.class.isNestmateOf(Outer.class)).equals(true);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCheckNestmatesForUnrelatedClasses_thenGetFalse() {
|
||||
is(Outer.Inner.class.isNestmateOf(Outer.class)).equals(false);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetNestMembersForNestedClasses_thenGetAllNestedClasses() {
|
||||
Set<String> nestMembers = Arrays.stream(Outer.Inner.class.getNestMembers())
|
||||
.map(Class::getName)
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
is(nestMembers.size()).equals(2);
|
||||
|
||||
assertTrue(nestMembers.contains("com.baeldung.Outer"));
|
||||
assertTrue(nestMembers.contains("com.baeldung.Outer$Inner"));
|
||||
}
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package com.baeldung.benchmark;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
|
||||
public class IntegerListFilterUnitTest {
|
||||
|
||||
private IntegerListFilter integerListFilter;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
integerListFilter = new IntegerListFilter();
|
||||
integerListFilter.setup();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenBenchmarkIsExecute_thenJDKListsMustBeOfSameSize() {
|
||||
assertEquals(integerListFilter.jdkList().size(), integerListFilter.jdkListParallel().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenBenchmarkIsExecute_thenMutableListsMustBeOfSameSize() {
|
||||
assertEquals(integerListFilter.ecMutableList().size(), integerListFilter.ecMutableListParallel().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenBenchmarkIsExecute_thenPrimitiveListsMustBeOfSameSize() {
|
||||
assertEquals(integerListFilter.ecPrimitive().size(), integerListFilter.ecPrimitiveParallel().size());
|
||||
}
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package com.baeldung.benchmark;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
|
||||
public class IntegerListSumUnitTest {
|
||||
|
||||
private IntegerListSum integerListSum;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
integerListSum = new IntegerListSum();
|
||||
integerListSum.setup();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenBenchmarkIsExecute_thenJDKListsMustHaveSameValue() {
|
||||
assertEquals(integerListSum.jdkList(), integerListSum.jdkListParallel());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenBenchmarkIsExecute_thenMutableListsMustHaveSameValue() {
|
||||
assertEquals(integerListSum.ecMutableList(), integerListSum.ecMutableListParallel());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenBenchmarkIsExecute_thenPrimitiveListsMustHaveSameValue() {
|
||||
assertEquals(integerListSum.ecPrimitive(), integerListSum.ecPrimitiveParallel());
|
||||
}
|
||||
}
|
||||
+240
@@ -0,0 +1,240 @@
|
||||
package com.baeldung.java11.httpclient.test;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.containsString;
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.Authenticator;
|
||||
import java.net.CookieManager;
|
||||
import java.net.CookiePolicy;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.PasswordAuthentication;
|
||||
import java.net.ProxySelector;
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.net.http.HttpResponse.BodyHandlers;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class HttpClientUnitTest {
|
||||
|
||||
@Test
|
||||
public void shouldReturnSampleDataContentWhenConnectViaSystemProxy() throws IOException, InterruptedException, URISyntaxException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://postman-echo.com/post"))
|
||||
.headers("Content-Type", "text/plain;charset=UTF-8")
|
||||
.POST(HttpRequest.BodyPublishers.ofString("Sample body"))
|
||||
.build();
|
||||
|
||||
|
||||
HttpResponse<String> response = HttpClient.newBuilder()
|
||||
.proxy(ProxySelector.getDefault())
|
||||
.build()
|
||||
.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
|
||||
assertThat(response.body(), containsString("Sample body"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldNotFollowRedirectWhenSetToDefaultNever() throws IOException, InterruptedException, URISyntaxException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("http://stackoverflow.com"))
|
||||
.version(HttpClient.Version.HTTP_1_1)
|
||||
.GET()
|
||||
.build();
|
||||
HttpResponse<String> response = HttpClient.newBuilder()
|
||||
.build()
|
||||
.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_MOVED_PERM));
|
||||
assertTrue(response.headers().map().get("location").stream().anyMatch("https://stackoverflow.com/"::equals));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldFollowRedirectWhenSetToAlways() throws IOException, InterruptedException, URISyntaxException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("http://stackoverflow.com"))
|
||||
.version(HttpClient.Version.HTTP_1_1)
|
||||
.GET()
|
||||
.build();
|
||||
HttpResponse<String> response = HttpClient.newBuilder()
|
||||
.followRedirects(HttpClient.Redirect.ALWAYS)
|
||||
.build()
|
||||
.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
|
||||
assertThat(response.request()
|
||||
.uri()
|
||||
.toString(), equalTo("https://stackoverflow.com/"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldReturnOKStatusForAuthenticatedAccess() throws URISyntaxException, IOException, InterruptedException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://postman-echo.com/basic-auth"))
|
||||
.GET()
|
||||
.build();
|
||||
HttpResponse<String> response = HttpClient.newBuilder()
|
||||
.authenticator(new Authenticator() {
|
||||
@Override
|
||||
protected PasswordAuthentication getPasswordAuthentication() {
|
||||
return new PasswordAuthentication("postman", "password".toCharArray());
|
||||
}
|
||||
})
|
||||
.build()
|
||||
.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldSendRequestAsync() throws URISyntaxException, InterruptedException, ExecutionException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://postman-echo.com/post"))
|
||||
.headers("Content-Type", "text/plain;charset=UTF-8")
|
||||
.POST(HttpRequest.BodyPublishers.ofString("Sample body"))
|
||||
.build();
|
||||
CompletableFuture<HttpResponse<String>> response = HttpClient.newBuilder()
|
||||
.build()
|
||||
.sendAsync(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
assertThat(response.get()
|
||||
.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldUseJustTwoThreadWhenProcessingSendAsyncRequest() throws URISyntaxException, InterruptedException, ExecutionException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://postman-echo.com/get"))
|
||||
.GET()
|
||||
.build();
|
||||
|
||||
ExecutorService executorService = Executors.newFixedThreadPool(2);
|
||||
|
||||
CompletableFuture<HttpResponse<String>> response1 = HttpClient.newBuilder()
|
||||
.executor(executorService)
|
||||
.build()
|
||||
.sendAsync(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
CompletableFuture<HttpResponse<String>> response2 = HttpClient.newBuilder()
|
||||
.executor(executorService)
|
||||
.build()
|
||||
.sendAsync(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
CompletableFuture<HttpResponse<String>> response3 = HttpClient.newBuilder()
|
||||
.executor(executorService)
|
||||
.build()
|
||||
.sendAsync(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
CompletableFuture.allOf(response1, response2, response3)
|
||||
.join();
|
||||
|
||||
assertThat(response1.get()
|
||||
.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
|
||||
assertThat(response2.get()
|
||||
.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
|
||||
assertThat(response3.get()
|
||||
.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldNotStoreCookieWhenPolicyAcceptNone() throws URISyntaxException, IOException, InterruptedException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://postman-echo.com/get"))
|
||||
.GET()
|
||||
.build();
|
||||
|
||||
HttpClient httpClient = HttpClient.newBuilder()
|
||||
.cookieHandler(new CookieManager(null, CookiePolicy.ACCEPT_NONE))
|
||||
.build();
|
||||
|
||||
httpClient.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
assertTrue(httpClient.cookieHandler()
|
||||
.isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldStoreCookieWhenPolicyAcceptAll() throws URISyntaxException, IOException, InterruptedException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://postman-echo.com/get"))
|
||||
.GET()
|
||||
.build();
|
||||
|
||||
HttpClient httpClient = HttpClient.newBuilder()
|
||||
.cookieHandler(new CookieManager(null, CookiePolicy.ACCEPT_ALL))
|
||||
.build();
|
||||
|
||||
httpClient.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
assertTrue(httpClient.cookieHandler()
|
||||
.isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldProcessMultipleRequestViaStream() throws URISyntaxException, ExecutionException, InterruptedException {
|
||||
List<URI> targets = Arrays.asList(new URI("https://postman-echo.com/get?foo1=bar1"), new URI("https://postman-echo.com/get?foo2=bar2"));
|
||||
|
||||
HttpClient client = HttpClient.newHttpClient();
|
||||
|
||||
List<CompletableFuture<String>> futures = targets.stream()
|
||||
.map(target -> client.sendAsync(HttpRequest.newBuilder(target)
|
||||
.GET()
|
||||
.build(), HttpResponse.BodyHandlers.ofString())
|
||||
.thenApply(response -> response.body()))
|
||||
.collect(Collectors.toList());
|
||||
|
||||
CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]))
|
||||
.join();
|
||||
|
||||
if (futures.get(0)
|
||||
.get()
|
||||
.contains("foo1")) {
|
||||
assertThat(futures.get(0)
|
||||
.get(), containsString("bar1"));
|
||||
assertThat(futures.get(1)
|
||||
.get(), containsString("bar2"));
|
||||
} else {
|
||||
assertThat(futures.get(1)
|
||||
.get(), containsString("bar2"));
|
||||
assertThat(futures.get(1)
|
||||
.get(), containsString("bar1"));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void completeExceptionallyExample() {
|
||||
CompletableFuture<String> cf = CompletableFuture.completedFuture("message").thenApplyAsync(String::toUpperCase,
|
||||
CompletableFuture.delayedExecutor(1, TimeUnit.SECONDS));
|
||||
CompletableFuture<String> exceptionHandler = cf.handle((s, th) -> { return (th != null) ? "message upon cancel" : ""; });
|
||||
cf.completeExceptionally(new RuntimeException("completed exceptionally"));
|
||||
assertTrue("Was not completed exceptionally", cf.isCompletedExceptionally());
|
||||
try {
|
||||
cf.join();
|
||||
fail("Should have thrown an exception");
|
||||
} catch (CompletionException ex) { // just for testing
|
||||
assertEquals("completed exceptionally", ex.getCause().getMessage());
|
||||
}
|
||||
|
||||
assertEquals("message upon cancel", exceptionHandler.join());
|
||||
}
|
||||
|
||||
}
|
||||
+174
@@ -0,0 +1,174 @@
|
||||
package com.baeldung.java11.httpclient.test;
|
||||
|
||||
import static java.time.temporal.ChronoUnit.SECONDS;
|
||||
import static org.hamcrest.CoreMatchers.containsString;
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.nio.file.Paths;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.time.Duration;
|
||||
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
public class HttpRequestUnitTest {
|
||||
|
||||
@Test
|
||||
public void shouldReturnStatusOKWhenSendGetRequest() throws IOException, InterruptedException, URISyntaxException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://postman-echo.com/get"))
|
||||
.GET()
|
||||
.build();
|
||||
|
||||
HttpResponse<String> response = HttpClient.newHttpClient()
|
||||
.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldUseHttp2WhenWebsiteUsesHttp2() throws IOException, InterruptedException, URISyntaxException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://stackoverflow.com"))
|
||||
.version(HttpClient.Version.HTTP_2)
|
||||
.GET()
|
||||
.build();
|
||||
HttpResponse<String> response = HttpClient.newHttpClient()
|
||||
.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
|
||||
assertThat(response.version(), equalTo(HttpClient.Version.HTTP_2));
|
||||
}
|
||||
|
||||
/*
|
||||
* This test will fail as soon as the given URL returns a HTTP 2 response.
|
||||
* Therefore, let's leave it ignored.
|
||||
* */
|
||||
@Test
|
||||
@Ignore
|
||||
public void shouldFallbackToHttp1_1WhenWebsiteDoesNotUseHttp2() throws IOException, InterruptedException, URISyntaxException, NoSuchAlgorithmException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://postman-echo.com/get"))
|
||||
.version(HttpClient.Version.HTTP_2)
|
||||
.GET()
|
||||
.build();
|
||||
|
||||
HttpResponse<String> response = HttpClient.newHttpClient()
|
||||
.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
assertThat(response.version(), equalTo(HttpClient.Version.HTTP_1_1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldReturnStatusOKWhenSendGetRequestWithDummyHeaders() throws IOException, InterruptedException, URISyntaxException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://postman-echo.com/get"))
|
||||
.headers("key1", "value1", "key2", "value2")
|
||||
.GET()
|
||||
.build();
|
||||
|
||||
HttpResponse<String> response = HttpClient.newHttpClient()
|
||||
.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldReturnStatusOKWhenSendGetRequestTimeoutSet() throws IOException, InterruptedException, URISyntaxException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://postman-echo.com/get"))
|
||||
.timeout(Duration.of(10, SECONDS))
|
||||
.GET()
|
||||
.build();
|
||||
|
||||
HttpResponse<String> response = HttpClient.newHttpClient()
|
||||
.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldReturnNoContentWhenPostWithNoBody() throws IOException, InterruptedException, URISyntaxException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://postman-echo.com/post"))
|
||||
.POST(HttpRequest.BodyPublishers.noBody())
|
||||
.build();
|
||||
|
||||
HttpResponse<String> response = HttpClient.newHttpClient()
|
||||
.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldReturnSampleDataContentWhenPostWithBodyText() throws IOException, InterruptedException, URISyntaxException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://postman-echo.com/post"))
|
||||
.headers("Content-Type", "text/plain;charset=UTF-8")
|
||||
.POST(HttpRequest.BodyPublishers.ofString("Sample request body"))
|
||||
.build();
|
||||
|
||||
HttpResponse<String> response = HttpClient.newHttpClient()
|
||||
.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
|
||||
assertThat(response.body(), containsString("Sample request body"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldReturnSampleDataContentWhenPostWithInputStream() throws IOException, InterruptedException, URISyntaxException {
|
||||
byte[] sampleData = "Sample request body".getBytes();
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://postman-echo.com/post"))
|
||||
.headers("Content-Type", "text/plain;charset=UTF-8")
|
||||
.POST(HttpRequest.BodyPublishers.ofInputStream(() -> new ByteArrayInputStream(sampleData)))
|
||||
.build();
|
||||
|
||||
HttpResponse<String> response = HttpClient.newHttpClient()
|
||||
.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
|
||||
assertThat(response.body(), containsString("Sample request body"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldReturnSampleDataContentWhenPostWithByteArrayProcessorStream() throws IOException, InterruptedException, URISyntaxException {
|
||||
byte[] sampleData = "Sample request body".getBytes();
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://postman-echo.com/post"))
|
||||
.headers("Content-Type", "text/plain;charset=UTF-8")
|
||||
.POST(HttpRequest.BodyPublishers.ofByteArray(sampleData))
|
||||
.build();
|
||||
|
||||
HttpResponse<String> response = HttpClient.newHttpClient()
|
||||
.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
|
||||
assertThat(response.body(), containsString("Sample request body"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldReturnSampleDataContentWhenPostWithFileProcessorStream() throws IOException, InterruptedException, URISyntaxException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://postman-echo.com/post"))
|
||||
.headers("Content-Type", "text/plain;charset=UTF-8")
|
||||
.POST(HttpRequest.BodyPublishers.ofFile(Paths.get("src/test/resources/sample.txt")))
|
||||
.build();
|
||||
|
||||
HttpResponse<String> response = HttpClient.newHttpClient()
|
||||
.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
|
||||
assertThat(response.body(), containsString("Sample file content"));
|
||||
}
|
||||
|
||||
}
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
package com.baeldung.java11.httpclient.test;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class HttpResponseUnitTest {
|
||||
|
||||
@Test
|
||||
public void shouldReturnStatusOKWhenSendGetRequest() throws IOException, InterruptedException, URISyntaxException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://postman-echo.com/get"))
|
||||
.version(HttpClient.Version.HTTP_2)
|
||||
.GET()
|
||||
.build();
|
||||
|
||||
HttpResponse<String> response = HttpClient.newBuilder()
|
||||
.followRedirects(HttpClient.Redirect.NORMAL)
|
||||
.build()
|
||||
.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
|
||||
assertNotNull(response.body());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldResponseURIDifferentThanRequestUIRWhenRedirect() throws IOException, InterruptedException, URISyntaxException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("http://stackoverflow.com"))
|
||||
.version(HttpClient.Version.HTTP_2)
|
||||
.GET()
|
||||
.build();
|
||||
HttpResponse<String> response = HttpClient.newBuilder()
|
||||
.followRedirects(HttpClient.Redirect.NORMAL)
|
||||
.build()
|
||||
.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
assertThat(request.uri()
|
||||
.toString(), equalTo("http://stackoverflow.com"));
|
||||
assertThat(response.uri()
|
||||
.toString(), equalTo("https://stackoverflow.com/"));
|
||||
}
|
||||
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package com.baeldung.optional;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link Optional} in Java 11.
|
||||
*/
|
||||
public class OptionalUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenAnEmptyOptional_isEmpty_thenBehavesAsExpected() {
|
||||
Optional<String> opt = Optional.of("Baeldung");
|
||||
assertFalse(opt.isEmpty());
|
||||
|
||||
opt = Optional.ofNullable(null);
|
||||
assertTrue(opt.isEmpty());
|
||||
}
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package com.baeldung.patternreuse;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class PatternJava11UnitTest {
|
||||
|
||||
@Test
|
||||
public void givenPreCompiledPattern_whenCallAsMatchPredicate_thenReturnMatchPredicateToMatchesPattern() {
|
||||
List<String> namesToValidate = Arrays.asList("Fabio Silva", "Fabio Luis Silva");
|
||||
Pattern firstLastNamePreCompiledPattern = Pattern.compile("[a-zA-Z]{3,} [a-zA-Z]{3,}");
|
||||
|
||||
Predicate<String> patternAsMatchPredicate = firstLastNamePreCompiledPattern.asMatchPredicate();
|
||||
List<String> validatedNames = namesToValidate.stream()
|
||||
.filter(patternAsMatchPredicate)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertTrue(validatedNames.contains("Fabio Silva"));
|
||||
assertFalse(validatedNames.contains("Fabio Luis Silva"));
|
||||
}
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
package com.baeldung.predicate.not;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static java.util.function.Predicate.not;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class PersonUnitTest {
|
||||
private List<Person> people;
|
||||
|
||||
@BeforeEach
|
||||
void preparePeople() {
|
||||
people = Arrays.asList(
|
||||
new Person(1),
|
||||
new Person(18),
|
||||
new Person(2)
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenPeople_whenFilterIsAdult_thenOneResult() {
|
||||
List<Person> adults = people.stream()
|
||||
.filter(Person::isAdult)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertThat(adults).size().isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenPeople_whenFilterIsAdultNegated_thenTwoResults() {
|
||||
List<Person> nonAdults = people.stream()
|
||||
.filter(person -> !person.isAdult())
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertThat(nonAdults).size().isEqualTo(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenPeople_whenFilterIsNotAdult_thenTwoResults() {
|
||||
List<Person> nonAdults = people.stream()
|
||||
.filter(Person::isNotAdult)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertThat(nonAdults).size().isEqualTo(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenPeople_whenFilterNotIsAdult_thenTwoResults() {
|
||||
List<Person> nonAdults = people.stream()
|
||||
.filter(not(Person::isAdult))
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertThat(nonAdults).size().isEqualTo(2);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
Sample file content
|
||||
Reference in New Issue
Block a user