BAEL-635 Overview of Spring 5 (#1633)

* Overview of Spring 5

* Overview of Spring 5

* BAEL-635 Formatting
This commit is contained in:
Thangtq211
2017-04-11 20:27:30 +07:00
committed by pedja4
parent 3286018dd2
commit e32c6e5f38
13 changed files with 684 additions and 137 deletions

View File

@@ -7,7 +7,7 @@ import org.springframework.boot.web.server.WebServer;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.test.web.reactive.server.WebTestClient;
//import org.springframework.test.web.reactive.server.WebTestClient;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.reactive.function.BodyInserters;
@@ -15,140 +15,141 @@ import org.springframework.web.reactive.function.BodyInserters;
import static org.springframework.web.reactive.function.BodyInserters.fromObject;
import static org.springframework.web.reactive.function.BodyInserters.fromResource;
// TODO The class does not compile, WebTestClient cannot be resolved. Missing dependency?
public class FunctionalWebApplicationIntegrationTest {
private static WebTestClient client;
private static WebServer server;
@BeforeClass
public static void setup() throws Exception {
server = new FunctionalWebApplication().start();
client = WebTestClient
.bindToServer()
.baseUrl("http://localhost:" + server.getPort())
.build();
}
@AfterClass
public static void destroy() {
server.stop();
}
@Test
public void givenRouter_whenGetTest_thenGotHelloWorld() throws Exception {
client
.get()
.uri("/test")
.exchange()
.expectStatus()
.isOk()
.expectBody(String.class)
.value()
.isEqualTo("helloworld");
}
@Test
public void givenIndexFilter_whenRequestRoot_thenRewrittenToTest() throws Exception {
client
.get()
.uri("/")
.exchange()
.expectStatus()
.isOk()
.expectBody(String.class)
.value()
.isEqualTo("helloworld");
}
@Test
public void givenLoginForm_whenPostValidToken_thenSuccess() throws Exception {
MultiValueMap<String, String> formData = new LinkedMultiValueMap<>(1);
formData.add("user", "baeldung");
formData.add("token", "you_know_what_to_do");
client
.post()
.uri("/login")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.exchange(BodyInserters.fromFormData(formData))
.expectStatus()
.isOk()
.expectBody(String.class)
.value()
.isEqualTo("welcome back!");
}
@Test
public void givenLoginForm_whenRequestWithInvalidToken_thenFail() throws Exception {
MultiValueMap<String, String> formData = new LinkedMultiValueMap<>(2);
formData.add("user", "baeldung");
formData.add("token", "try_again");
client
.post()
.uri("/login")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.exchange(BodyInserters.fromFormData(formData))
.expectStatus()
.isBadRequest();
}
@Test
public void givenUploadForm_whenRequestWithMultipartData_thenSuccess() throws Exception {
Resource resource = new ClassPathResource("/baeldung-weekly.png");
client
.post()
.uri("/upload")
.contentType(MediaType.MULTIPART_FORM_DATA)
.exchange(fromResource(resource))
.expectStatus()
.isOk()
.expectBody(String.class)
.value()
.isEqualTo(String.valueOf(resource.contentLength()));
}
@Test
public void givenActors_whenAddActor_thenAdded() throws Exception {
client
.get()
.uri("/actor")
.exchange()
.expectStatus()
.isOk()
.expectBody(Actor.class)
.list()
.hasSize(2);
client
.post()
.uri("/actor")
.exchange(fromObject(new Actor("Clint", "Eastwood")))
.expectStatus()
.isOk();
client
.get()
.uri("/actor")
.exchange()
.expectStatus()
.isOk()
.expectBody(Actor.class)
.list()
.hasSize(3);
}
@Test
public void givenResources_whenAccess_thenGot() throws Exception {
client
.get()
.uri("/files/hello.txt")
.exchange()
.expectStatus()
.isOk()
.expectBody(String.class)
.value()
.isEqualTo("hello");
}
// private static WebTestClient client;
// private static WebServer server;
//
// @BeforeClass
// public static void setup() throws Exception {
// server = new FunctionalWebApplication().start();
// client = WebTestClient
// .bindToServer()
// .baseUrl("http://localhost:" + server.getPort())
// .build();
// }
//
// @AfterClass
// public static void destroy() {
// server.stop();
// }
//
// @Test
// public void givenRouter_whenGetTest_thenGotHelloWorld() throws Exception {
// client
// .get()
// .uri("/test")
// .exchange()
// .expectStatus()
// .isOk()
// .expectBody(String.class)
// .value()
// .isEqualTo("helloworld");
// }
//
// @Test
// public void givenIndexFilter_whenRequestRoot_thenRewrittenToTest() throws Exception {
// client
// .get()
// .uri("/")
// .exchange()
// .expectStatus()
// .isOk()
// .expectBody(String.class)
// .value()
// .isEqualTo("helloworld");
// }
//
// @Test
// public void givenLoginForm_whenPostValidToken_thenSuccess() throws Exception {
// MultiValueMap<String, String> formData = new LinkedMultiValueMap<>(1);
// formData.add("user", "baeldung");
// formData.add("token", "you_know_what_to_do");
//
// client
// .post()
// .uri("/login")
// .contentType(MediaType.APPLICATION_FORM_URLENCODED)
// .exchange(BodyInserters.fromFormData(formData))
// .expectStatus()
// .isOk()
// .expectBody(String.class)
// .value()
// .isEqualTo("welcome back!");
// }
//
// @Test
// public void givenLoginForm_whenRequestWithInvalidToken_thenFail() throws Exception {
// MultiValueMap<String, String> formData = new LinkedMultiValueMap<>(2);
// formData.add("user", "baeldung");
// formData.add("token", "try_again");
//
// client
// .post()
// .uri("/login")
// .contentType(MediaType.APPLICATION_FORM_URLENCODED)
// .exchange(BodyInserters.fromFormData(formData))
// .expectStatus()
// .isBadRequest();
// }
//
// @Test
// public void givenUploadForm_whenRequestWithMultipartData_thenSuccess() throws Exception {
// Resource resource = new ClassPathResource("/baeldung-weekly.png");
// client
// .post()
// .uri("/upload")
// .contentType(MediaType.MULTIPART_FORM_DATA)
// .exchange(fromResource(resource))
// .expectStatus()
// .isOk()
// .expectBody(String.class)
// .value()
// .isEqualTo(String.valueOf(resource.contentLength()));
// }
//
// @Test
// public void givenActors_whenAddActor_thenAdded() throws Exception {
// client
// .get()
// .uri("/actor")
// .exchange()
// .expectStatus()
// .isOk()
// .expectBody(Actor.class)
// .list()
// .hasSize(2);
//
// client
// .post()
// .uri("/actor")
// .exchange(fromObject(new Actor("Clint", "Eastwood")))
// .expectStatus()
// .isOk();
//
// client
// .get()
// .uri("/actor")
// .exchange()
// .expectStatus()
// .isOk()
// .expectBody(Actor.class)
// .list()
// .hasSize(3);
// }
//
// @Test
// public void givenResources_whenAccess_thenGot() throws Exception {
// client
// .get()
// .uri("/files/hello.txt")
// .exchange()
// .expectStatus()
// .isOk()
// .expectBody(String.class)
// .value()
// .isEqualTo("hello");
// }
}

View File

@@ -0,0 +1,38 @@
package com.baeldung.jupiter;
import com.baeldung.web.reactive.Task;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@SpringJUnit5Config(TestConfig.class)
@DisplayName("@SpringJUnit5Config Tests")
class Spring5JUnit5ComposedAnnotationTests {
@Autowired
Task task;
@Autowired
List<Task> tasks;
@Test
@DisplayName("ApplicationContext injected into method")
void givenAMethodName_whenInjecting_thenApplicationContextInjectedIntoMethod(ApplicationContext applicationContext) {
assertNotNull(applicationContext, "ApplicationContext should have been injected into method by Spring");
assertEquals(this.task, applicationContext.getBean("taskName", Task.class));
}
@Test
@DisplayName("Spring @Beans injected into fields")
void givenAnObject_whenInjecting_thenSpringBeansInjected() {
assertNotNull(task, "Task should have been @Autowired by Spring");
assertEquals("taskName", task.getName(), "Task's name");
assertEquals(1, tasks.size(), "Number of Tasks in context");
}
}

View File

@@ -0,0 +1,29 @@
package com.baeldung.jupiter;
import com.baeldung.IntegrationTestExample1;
import com.baeldung.IntegrationTestExample2;
import org.junit.experimental.ParallelComputer;
import org.junit.jupiter.api.Test;
import org.junit.runner.Computer;
import org.junit.runner.JUnitCore;
public class Spring5JUnit5ParallelTest {
@Test
public void givenTwoTestClasses_whenJUnitRunParallel_thenTheTestsExecutingParallel() {
final Class<?>[] classes = {
IntegrationTestExample1.class, IntegrationTestExample2.class
};
JUnitCore.runClasses(new ParallelComputer(true, true), classes);
}
@Test
public void givenTwoTestClasses_whenJUnitRunParallel_thenTheTestsExecutingLinear() {
final Class<?>[] classes = {
IntegrationTestExample1.class, IntegrationTestExample2.class
};
JUnitCore.runClasses(new Computer(), classes);
}
}

View File

@@ -0,0 +1,27 @@
package com.baeldung.jupiter;
import com.baeldung.web.reactive.Task;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import org.junit.jupiter.api.Test;
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = TestConfig.class)
class Spring5JUnit5Tests {
@Autowired
Task task;
@Test
void givenAMethodName_whenInjecting_thenApplicationContextInjectedIntoMetho(ApplicationContext applicationContext) {
assertNotNull(applicationContext, "ApplicationContext should have been injected by Spring");
assertEquals(this.task, applicationContext.getBean("taskName", Task.class));
}
}

View File

@@ -0,0 +1,33 @@
package com.baeldung.jupiter;
import org.junit.jupiter.api.Test;
import java.util.function.Supplier;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class Spring5Java8NewFeaturesTest {
@FunctionalInterface
public interface FunctionalInterfaceExample<Input, Result> {
Result reverseString(Input input);
}
public class StringUtils{
public FunctionalInterfaceExample<String, String>
functionLambdaString = s -> {
return Pattern.compile(" +").splitAsStream(s)
.map(word->new StringBuilder(word).reverse())
.collect(Collectors.joining(" "));
};
}
@Test
void givenStringUtil_whenSupplierCall_thenFunctionalInterfaceReverseString()
throws Exception {
Supplier<StringUtils> stringUtilsSupplier = StringUtils::new;
assertEquals(stringUtilsSupplier.get().functionLambdaString
.reverseString("hello"), "olleh");
}
}

View File

@@ -0,0 +1,110 @@
package com.baeldung.jupiter;
import com.baeldung.web.reactive.Task;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.springframework.http.server.reactive.HttpHandler;
import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.ClientRequest;
import org.springframework.web.reactive.function.client.ExchangeFunction;
import org.springframework.web.reactive.function.client.ExchangeFunctions;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.ipc.netty.NettyContext;
import reactor.ipc.netty.http.server.HttpServer;
import java.net.URI;
import java.time.Duration;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.web.reactive.function.server.RequestPredicates.GET;
import static org.springframework.web.reactive.function.server.RequestPredicates.POST;
public class Spring5ReactiveServerClientTest {
private static NettyContext nettyContext;
@BeforeAll
public static void setUp() throws Exception {
HttpServer server = HttpServer.create("localhost", 8080);
RouterFunction<?> route = RouterFunctions
.route(POST("/task/process"), request -> ServerResponse
.ok()
.body(request
.bodyToFlux(Task.class)
.map(ll -> new Task("TaskName", 1)), Task.class))
.and(RouterFunctions.route(GET("/task"), request -> ServerResponse
.ok()
.body(Mono.just("server is alive"), String.class)));
HttpHandler httpHandler = RouterFunctions.toHttpHandler(route);
ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(httpHandler);
nettyContext = server
.newHandler(adapter)
.block();
}
@AfterAll
public static void shutDown() {
nettyContext.dispose();
}
@Test
public void givenCheckTask_whenServerHandle_thenServerResponseALiveString() throws Exception {
WebClient client = WebClient.create("http://localhost:8080");
Mono<String> result = client
.get()
.uri("/task")
.exchange()
.then(response -> response.bodyToMono(String.class));
assertThat(result.block()).isInstanceOf(String.class);
}
@Test
public void givenThreeTasks_whenServerHandleTheTasks_thenServerResponseATask() throws Exception {
URI uri = URI.create("http://localhost:8080/task/process");
ExchangeFunction exchange = ExchangeFunctions.create(new ReactorClientHttpConnector());
ClientRequest request = ClientRequest
.method(HttpMethod.POST, uri)
.body(BodyInserters.fromPublisher(getLatLngs(), Task.class))
.build();
Flux<Task> taskResponse = exchange
.exchange(request)
.flatMap(response -> response.bodyToFlux(Task.class));
assertThat(taskResponse.blockFirst()).isInstanceOf(Task.class);
}
@Test
public void givenCheckTask_whenServerHandle_thenOragicServerResponseALiveString() throws Exception {
URI uri = URI.create("http://localhost:8080/task");
ExchangeFunction exchange = ExchangeFunctions.create(new ReactorClientHttpConnector());
ClientRequest request = ClientRequest
.method(HttpMethod.GET, uri)
.body(BodyInserters.fromPublisher(getLatLngs(), Task.class))
.build();
Flux<String> taskResponse = exchange
.exchange(request)
.flatMap(response -> response.bodyToFlux(String.class));
assertThat(taskResponse.blockFirst()).isInstanceOf(String.class);
}
private static Flux<Task> getLatLngs() {
return Flux
.range(0, 3)
.zipWith(Flux.interval(Duration.ofSeconds(1)))
.map(x -> new Task("taskname", 1))
.doOnNext(ll -> System.out.println("Produced: {}" + ll));
}
}