formatting work

This commit is contained in:
eugenp 2017-09-13 14:41:03 +03:00
parent 75c1003451
commit 0f22f7b82a
23 changed files with 334 additions and 386 deletions

View File

@ -14,16 +14,19 @@ public class LiveTest {
private static String APP_ROOT = "http://localhost:8081"; private static String APP_ROOT = "http://localhost:8081";
@Test @Test
public void givenUser_whenResourceCreatedWithNullName_then400BadRequest() { public void givenUser_whenResourceCreatedWithNullName_then400BadRequest() {
final Response response = givenAuth("user", "pass").contentType(MediaType.APPLICATION_JSON.toString()).body(resourceWithNullName()).post(APP_ROOT + "/foos"); final Response response = givenAuth("user", "pass").contentType(MediaType.APPLICATION_JSON.toString())
.body(resourceWithNullName())
.post(APP_ROOT + "/foos");
assertEquals(400, response.getStatusCode()); assertEquals(400, response.getStatusCode());
} }
@Test @Test
public void givenUser_whenResourceCreated_then201Created() { public void givenUser_whenResourceCreated_then201Created() {
final Response response = givenAuth("user", "pass").contentType(MediaType.APPLICATION_JSON.toString()).body(resourceString()).post(APP_ROOT + "/foos"); final Response response = givenAuth("user", "pass").contentType(MediaType.APPLICATION_JSON.toString())
.body(resourceString())
.post(APP_ROOT + "/foos");
assertEquals(201, response.getStatusCode()); assertEquals(201, response.getStatusCode());
} }
@ -33,8 +36,6 @@ public class LiveTest {
assertEquals(200, response.getStatusCode()); assertEquals(200, response.getStatusCode());
}*/ }*/
// //
private final String resourceWithNullName() { private final String resourceWithNullName() {
@ -46,7 +47,10 @@ public class LiveTest {
} }
private final RequestSpecification givenAuth(String username, String password) { private final RequestSpecification givenAuth(String username, String password) {
return RestAssured.given().auth().preemptive().basic(username, password); return RestAssured.given()
.auth()
.preemptive()
.basic(username, password);
} }
} }

View File

@ -5,7 +5,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication @SpringBootApplication
@ComponentScan(basePackages = {"com.baeldung.web"}) @ComponentScan(basePackages = { "com.baeldung.web" })
public class Spring5Application { public class Spring5Application {
public static void main(String[] args) { public static void main(String[] args) {

View File

@ -17,27 +17,24 @@ import static org.springframework.web.reactive.function.server.ServerResponse.ok
public class FormHandler { public class FormHandler {
Mono<ServerResponse> handleLogin(ServerRequest request) { Mono<ServerResponse> handleLogin(ServerRequest request) {
return request return request.body(toFormData())
.body(toFormData())
.map(MultiValueMap::toSingleValueMap) .map(MultiValueMap::toSingleValueMap)
.filter(formData -> "baeldung".equals(formData.get("user"))) .filter(formData -> "baeldung".equals(formData.get("user")))
.filter(formData -> "you_know_what_to_do".equals(formData.get("token"))) .filter(formData -> "you_know_what_to_do".equals(formData.get("token")))
.flatMap(formData -> ok().body(Mono.just("welcome back!"), String.class)) .flatMap(formData -> ok().body(Mono.just("welcome back!"), String.class))
.switchIfEmpty(ServerResponse.badRequest().build()); .switchIfEmpty(ServerResponse.badRequest()
.build());
} }
Mono<ServerResponse> handleUpload(ServerRequest request) { Mono<ServerResponse> handleUpload(ServerRequest request) {
return request return request.body(toDataBuffers())
.body(toDataBuffers())
.collectList() .collectList()
.flatMap(dataBuffers -> ok() .flatMap(dataBuffers -> ok().body(fromObject(extractData(dataBuffers).toString())));
.body(fromObject(extractData(dataBuffers).toString())));
} }
private AtomicLong extractData(List<DataBuffer> dataBuffers) { private AtomicLong extractData(List<DataBuffer> dataBuffers) {
AtomicLong atomicLong = new AtomicLong(0); AtomicLong atomicLong = new AtomicLong(0);
dataBuffers.forEach(d -> atomicLong.addAndGet(d dataBuffers.forEach(d -> atomicLong.addAndGet(d.asByteBuffer()
.asByteBuffer()
.array().length)); .array().length));
return atomicLong; return atomicLong;
} }

View File

@ -40,13 +40,11 @@ public class FunctionalSpringBootApplication {
private RouterFunction<ServerResponse> routingFunction() { private RouterFunction<ServerResponse> routingFunction() {
FormHandler formHandler = new FormHandler(); FormHandler formHandler = new FormHandler();
RouterFunction<ServerResponse> restfulRouter = route(GET("/"), serverRequest -> ok().body(Flux.fromIterable(actors), Actor.class)).andRoute(POST("/"), serverRequest -> serverRequest RouterFunction<ServerResponse> restfulRouter = route(GET("/"), serverRequest -> ok().body(Flux.fromIterable(actors), Actor.class)).andRoute(POST("/"), serverRequest -> serverRequest.bodyToMono(Actor.class)
.bodyToMono(Actor.class)
.doOnNext(actors::add) .doOnNext(actors::add)
.then(ok().build())); .then(ok().build()));
return route(GET("/test"), serverRequest -> ok().body(fromObject("helloworld"))) return route(GET("/test"), serverRequest -> ok().body(fromObject("helloworld"))).andRoute(POST("/login"), formHandler::handleLogin)
.andRoute(POST("/login"), formHandler::handleLogin)
.andRoute(POST("/upload"), formHandler::handleUpload) .andRoute(POST("/upload"), formHandler::handleUpload)
.and(RouterFunctions.resources("/files/**", new ClassPathResource("files/"))) .and(RouterFunctions.resources("/files/**", new ClassPathResource("files/")))
.andNest(path("/actor"), restfulRouter) .andNest(path("/actor"), restfulRouter)
@ -58,8 +56,7 @@ public class FunctionalSpringBootApplication {
@Bean @Bean
public ServletRegistrationBean servletRegistrationBean() throws Exception { public ServletRegistrationBean servletRegistrationBean() throws Exception {
HttpHandler httpHandler = WebHttpHandlerBuilder HttpHandler httpHandler = WebHttpHandlerBuilder.webHandler((WebHandler) toHttpHandler(routingFunction()))
.webHandler((WebHandler) toHttpHandler(routingFunction()))
.prependFilter(new IndexRewriteFilter()) .prependFilter(new IndexRewriteFilter())
.build(); .build();
ServletRegistrationBean registrationBean = new ServletRegistrationBean<>(new RootServlet(httpHandler), "/"); ServletRegistrationBean registrationBean = new ServletRegistrationBean<>(new RootServlet(httpHandler), "/");
@ -74,8 +71,7 @@ public class FunctionalSpringBootApplication {
static class SecurityConfig extends WebSecurityConfigurerAdapter { static class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override @Override
protected void configure(final HttpSecurity http) throws Exception { protected void configure(final HttpSecurity http) throws Exception {
http http.authorizeRequests()
.authorizeRequests()
.anyRequest() .anyRequest()
.permitAll(); .permitAll();
} }

View File

@ -33,13 +33,11 @@ public class FunctionalWebApplication {
private RouterFunction<ServerResponse> routingFunction() { private RouterFunction<ServerResponse> routingFunction() {
FormHandler formHandler = new FormHandler(); FormHandler formHandler = new FormHandler();
RouterFunction<ServerResponse> restfulRouter = route(GET("/"), serverRequest -> ok().body(Flux.fromIterable(actors), Actor.class)).andRoute(POST("/"), serverRequest -> serverRequest RouterFunction<ServerResponse> restfulRouter = route(GET("/"), serverRequest -> ok().body(Flux.fromIterable(actors), Actor.class)).andRoute(POST("/"), serverRequest -> serverRequest.bodyToMono(Actor.class)
.bodyToMono(Actor.class)
.doOnNext(actors::add) .doOnNext(actors::add)
.then(ok().build())); .then(ok().build()));
return route(GET("/test"), serverRequest -> ok().body(fromObject("helloworld"))) return route(GET("/test"), serverRequest -> ok().body(fromObject("helloworld"))).andRoute(POST("/login"), formHandler::handleLogin)
.andRoute(POST("/login"), formHandler::handleLogin)
.andRoute(POST("/upload"), formHandler::handleUpload) .andRoute(POST("/upload"), formHandler::handleUpload)
.and(RouterFunctions.resources("/files/**", new ClassPathResource("files/"))) .and(RouterFunctions.resources("/files/**", new ClassPathResource("files/")))
.andNest(path("/actor"), restfulRouter) .andNest(path("/actor"), restfulRouter)
@ -51,8 +49,7 @@ public class FunctionalWebApplication {
WebServer start() throws Exception { WebServer start() throws Exception {
WebHandler webHandler = (WebHandler) toHttpHandler(routingFunction()); WebHandler webHandler = (WebHandler) toHttpHandler(routingFunction());
HttpHandler httpHandler = WebHttpHandlerBuilder HttpHandler httpHandler = WebHttpHandlerBuilder.webHandler(webHandler)
.webHandler(webHandler)
.prependFilter(new IndexRewriteFilter()) .prependFilter(new IndexRewriteFilter())
.build(); .build();

View File

@ -11,15 +11,13 @@ class IndexRewriteFilter implements WebFilter {
@Override @Override
public Mono<Void> filter(ServerWebExchange serverWebExchange, WebFilterChain webFilterChain) { public Mono<Void> filter(ServerWebExchange serverWebExchange, WebFilterChain webFilterChain) {
ServerHttpRequest request = serverWebExchange.getRequest(); ServerHttpRequest request = serverWebExchange.getRequest();
if (request if (request.getURI()
.getURI()
.getPath() .getPath()
.equals("/")) { .equals("/")) {
return webFilterChain.filter(serverWebExchange return webFilterChain.filter(serverWebExchange.mutate()
.mutate() .request(builder -> builder.method(request.getMethod())
.request(builder -> builder .contextPath(request.getPath()
.method(request.getMethod()) .toString())
.contextPath(request.getPath().toString())
.path("/test")) .path("/test"))
.build()); .build());
} }

View File

@ -4,7 +4,7 @@ import java.util.Random;
public class MyService { public class MyService {
public int getRandomNumber(){ public int getRandomNumber() {
return (new Random().nextInt(10)); return (new Random().nextInt(10));
} }

View File

@ -28,8 +28,7 @@ import org.springframework.web.server.WebHandler;
public class RootServlet extends ServletHttpHandlerAdapter { public class RootServlet extends ServletHttpHandlerAdapter {
public RootServlet() { public RootServlet() {
this(WebHttpHandlerBuilder this(WebHttpHandlerBuilder.webHandler((WebHandler) toHttpHandler(routingFunction()))
.webHandler((WebHandler) toHttpHandler(routingFunction()))
.prependFilter(new IndexRewriteFilter()) .prependFilter(new IndexRewriteFilter())
.build()); .build());
} }
@ -44,38 +43,30 @@ public class RootServlet extends ServletHttpHandlerAdapter {
private static RouterFunction<?> routingFunction() { private static RouterFunction<?> routingFunction() {
return route(GET("/test"), serverRequest -> ok().body(fromObject("helloworld"))) return route(GET("/test"), serverRequest -> ok().body(fromObject("helloworld"))).andRoute(POST("/login"), serverRequest -> serverRequest.body(toFormData())
.andRoute(POST("/login"), serverRequest -> serverRequest
.body(toFormData())
.map(MultiValueMap::toSingleValueMap) .map(MultiValueMap::toSingleValueMap)
.map(formData -> { .map(formData -> {
System.out.println("form data: " + formData.toString()); System.out.println("form data: " + formData.toString());
if ("baeldung".equals(formData.get("user")) && "you_know_what_to_do".equals(formData.get("token"))) { if ("baeldung".equals(formData.get("user")) && "you_know_what_to_do".equals(formData.get("token"))) {
return ok() return ok().body(Mono.just("welcome back!"), String.class)
.body(Mono.just("welcome back!"), String.class)
.block(); .block();
} }
return ServerResponse return ServerResponse.badRequest()
.badRequest()
.build() .build()
.block(); .block();
})) }))
.andRoute(POST("/upload"), serverRequest -> serverRequest .andRoute(POST("/upload"), serverRequest -> serverRequest.body(toDataBuffers())
.body(toDataBuffers())
.collectList() .collectList()
.map(dataBuffers -> { .map(dataBuffers -> {
AtomicLong atomicLong = new AtomicLong(0); AtomicLong atomicLong = new AtomicLong(0);
dataBuffers.forEach(d -> atomicLong.addAndGet(d dataBuffers.forEach(d -> atomicLong.addAndGet(d.asByteBuffer()
.asByteBuffer()
.array().length)); .array().length));
System.out.println("data length:" + atomicLong.get()); System.out.println("data length:" + atomicLong.get());
return ok() return ok().body(fromObject(atomicLong.toString()))
.body(fromObject(atomicLong.toString()))
.block(); .block();
})) }))
.and(RouterFunctions.resources("/files/**", new ClassPathResource("files/"))) .and(RouterFunctions.resources("/files/**", new ClassPathResource("files/")))
.andNest(path("/actor"), route(GET("/"), serverRequest -> ok().body(Flux.fromIterable(actors), Actor.class)).andRoute(POST("/"), serverRequest -> serverRequest .andNest(path("/actor"), route(GET("/"), serverRequest -> ok().body(Flux.fromIterable(actors), Actor.class)).andRoute(POST("/"), serverRequest -> serverRequest.bodyToMono(Actor.class)
.bodyToMono(Actor.class)
.doOnNext(actors::add) .doOnNext(actors::add)
.then(ok().build()))) .then(ok().build())))
.filter((request, next) -> { .filter((request, next) -> {

View File

@ -27,15 +27,13 @@ abstract class ParameterAutowireUtils {
public static Object resolveDependency(Parameter parameter, Class<?> containingClass, ApplicationContext applicationContext) { public static Object resolveDependency(Parameter parameter, Class<?> containingClass, ApplicationContext applicationContext) {
boolean required = findMergedAnnotation(parameter, Autowired.class) boolean required = findMergedAnnotation(parameter, Autowired.class).map(Autowired::required)
.map(Autowired::required)
.orElse(true); .orElse(true);
MethodParameter methodParameter = (parameter.getDeclaringExecutable() instanceof Method ? MethodParameterFactory.createSynthesizingMethodParameter(parameter) : MethodParameterFactory.createMethodParameter(parameter)); MethodParameter methodParameter = (parameter.getDeclaringExecutable() instanceof Method ? MethodParameterFactory.createSynthesizingMethodParameter(parameter) : MethodParameterFactory.createMethodParameter(parameter));
DependencyDescriptor descriptor = new DependencyDescriptor(methodParameter, required); DependencyDescriptor descriptor = new DependencyDescriptor(methodParameter, required);
descriptor.setContainingClass(containingClass); descriptor.setContainingClass(containingClass);
return applicationContext return applicationContext.getAutowireCapableBeanFactory()
.getAutowireCapableBeanFactory()
.resolveDependency(descriptor, null); .resolveDependency(descriptor, null);
} }

View File

@ -26,10 +26,8 @@ public class SpringExtension implements BeforeAllCallback, AfterAllCallback, Tes
try { try {
getTestContextManager(context).afterTestClass(); getTestContextManager(context).afterTestClass();
} finally { } finally {
context context.getStore(namespace)
.getStore(namespace) .remove(context.getTestClass()
.remove(context
.getTestClass()
.get()); .get());
} }
} }
@ -42,8 +40,7 @@ public class SpringExtension implements BeforeAllCallback, AfterAllCallback, Tes
@Override @Override
public void beforeEach(TestExtensionContext context) throws Exception { public void beforeEach(TestExtensionContext context) throws Exception {
Object testInstance = context.getTestInstance(); Object testInstance = context.getTestInstance();
Method testMethod = context Method testMethod = context.getTestMethod()
.getTestMethod()
.get(); .get();
getTestContextManager(context).beforeTestMethod(testInstance, testMethod); getTestContextManager(context).beforeTestMethod(testInstance, testMethod);
} }
@ -51,11 +48,9 @@ public class SpringExtension implements BeforeAllCallback, AfterAllCallback, Tes
@Override @Override
public void afterEach(TestExtensionContext context) throws Exception { public void afterEach(TestExtensionContext context) throws Exception {
Object testInstance = context.getTestInstance(); Object testInstance = context.getTestInstance();
Method testMethod = context Method testMethod = context.getTestMethod()
.getTestMethod()
.get(); .get();
Throwable testException = context Throwable testException = context.getTestException()
.getTestException()
.orElse(null); .orElse(null);
getTestContextManager(context).afterTestMethod(testInstance, testMethod, testException); getTestContextManager(context).afterTestMethod(testInstance, testMethod, testException);
} }
@ -70,23 +65,20 @@ public class SpringExtension implements BeforeAllCallback, AfterAllCallback, Tes
@Override @Override
public Object resolve(ParameterContext parameterContext, ExtensionContext extensionContext) { public Object resolve(ParameterContext parameterContext, ExtensionContext extensionContext) {
Parameter parameter = parameterContext.getParameter(); Parameter parameter = parameterContext.getParameter();
Class<?> testClass = extensionContext Class<?> testClass = extensionContext.getTestClass()
.getTestClass()
.get(); .get();
ApplicationContext applicationContext = getApplicationContext(extensionContext); ApplicationContext applicationContext = getApplicationContext(extensionContext);
return ParameterAutowireUtils.resolveDependency(parameter, testClass, applicationContext); return ParameterAutowireUtils.resolveDependency(parameter, testClass, applicationContext);
} }
private ApplicationContext getApplicationContext(ExtensionContext context) { private ApplicationContext getApplicationContext(ExtensionContext context) {
return getTestContextManager(context) return getTestContextManager(context).getTestContext()
.getTestContext()
.getApplicationContext(); .getApplicationContext();
} }
private TestContextManager getTestContextManager(ExtensionContext context) { private TestContextManager getTestContextManager(ExtensionContext context) {
Assert.notNull(context, "ExtensionContext must not be null"); Assert.notNull(context, "ExtensionContext must not be null");
Class<?> testClass = context Class<?> testClass = context.getTestClass()
.getTestClass()
.get(); .get();
ExtensionContext.Store store = context.getStore(namespace); ExtensionContext.Store store = context.getStore(namespace);
return store.getOrComputeIfAbsent(testClass, TestContextManager::new, TestContextManager.class); return store.getOrComputeIfAbsent(testClass, TestContextManager::new, TestContextManager.class);

View File

@ -26,8 +26,7 @@ public @interface SpringJUnit5Config {
String[] locations() default {}; String[] locations() default {};
@AliasFor(annotation = ContextConfiguration.class) @AliasFor(annotation = ContextConfiguration.class)
Class<? extends ApplicationContextInitializer<? Class<? extends ApplicationContextInitializer<? extends ConfigurableApplicationContext>>[] initializers() default {};
extends ConfigurableApplicationContext>>[] initializers() default {};
@AliasFor(annotation = ContextConfiguration.class) @AliasFor(annotation = ContextConfiguration.class)
boolean inheritLocations() default true; boolean inheritLocations() default true;

View File

@ -20,7 +20,8 @@ public class DataSetupBean implements InitializingBean {
@Override @Override
public void afterPropertiesSet() throws Exception { public void afterPropertiesSet() throws Exception {
IntStream.range(1, 20).forEach(i -> repo.save(new Foo(randomAlphabetic(8)))); IntStream.range(1, 20)
.forEach(i -> repo.save(new Foo(randomAlphabetic(8))));
} }
} }

View File

@ -23,7 +23,8 @@ public class FooController {
@ResponseBody @ResponseBody
@Validated @Validated
public Foo findById(@PathVariable @Min(0) final long id) { public Foo findById(@PathVariable @Min(0) final long id) {
return repo.findById(id).orElse(null); return repo.findById(id)
.orElse(null);
} }
@GetMapping @GetMapping
@ -36,7 +37,8 @@ public class FooController {
@ResponseBody @ResponseBody
@Validated @Validated
public List<Foo> findPaginated(@RequestParam("page") @Min(0) final int page, @Max(100) @RequestParam("size") final int size) { public List<Foo> findPaginated(@RequestParam("page") @Min(0) final int page, @Max(100) @RequestParam("size") final int size) {
return repo.findAll(PageRequest.of(page, size)).getContent(); return repo.findAll(PageRequest.of(page, size))
.getContent();
} }
// API - write // API - write

View File

@ -23,9 +23,6 @@ public class Task {
@Override @Override
public String toString() { public String toString() {
return "Task{" + return "Task{" + "name='" + name + '\'' + ", id=" + id + '}';
"name='" + name + '\'' +
", id=" + id +
'}';
} }
} }

View File

@ -33,17 +33,17 @@ public class WebClientController {
WebClient.UriSpec<WebClient.RequestBodySpec> request2 = createWebClientWithServerURLAndDefaultValues().post(); WebClient.UriSpec<WebClient.RequestBodySpec> request2 = createWebClientWithServerURLAndDefaultValues().post();
// request body specifications // request body specifications
WebClient.RequestBodySpec uri1 = createWebClientWithServerURLAndDefaultValues().method(HttpMethod.POST).uri("/resource"); WebClient.RequestBodySpec uri1 = createWebClientWithServerURLAndDefaultValues().method(HttpMethod.POST)
WebClient.RequestBodySpec uri2 = createWebClientWithServerURLAndDefaultValues().post().uri(URI.create("/resource")); .uri("/resource");
WebClient.RequestBodySpec uri2 = createWebClientWithServerURLAndDefaultValues().post()
.uri(URI.create("/resource"));
// request header specification // request header specification
WebClient.RequestHeadersSpec<?> requestSpec1 = uri1.body(BodyInserters.fromPublisher(Mono.just("data"), String.class)); WebClient.RequestHeadersSpec<?> requestSpec1 = uri1.body(BodyInserters.fromPublisher(Mono.just("data"), String.class));
WebClient.RequestHeadersSpec<?> requestSpec2 = uri2.body(BodyInserters.fromObject("data")); WebClient.RequestHeadersSpec<?> requestSpec2 = uri2.body(BodyInserters.fromObject("data"));
// inserters // inserters
BodyInserter<Publisher<String>, ReactiveHttpOutputMessage> inserter1 = BodyInserters BodyInserter<Publisher<String>, ReactiveHttpOutputMessage> inserter1 = BodyInserters.fromPublisher(Subscriber::onComplete, String.class);
.fromPublisher(Subscriber::onComplete, String.class);
LinkedMultiValueMap<String, String> map = new LinkedMultiValueMap<>(); LinkedMultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("key1", "value1"); map.add("key1", "value1");
@ -53,8 +53,7 @@ public class WebClientController {
BodyInserter<String, ReactiveHttpOutputMessage> inserter3 = BodyInserters.fromObject("body"); BodyInserter<String, ReactiveHttpOutputMessage> inserter3 = BodyInserters.fromObject("body");
// responses // responses
WebClient.ResponseSpec response1 = uri1 WebClient.ResponseSpec response1 = uri1.body(inserter3)
.body(inserter3)
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML) .accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML)
.acceptCharset(Charset.forName("UTF-8")) .acceptCharset(Charset.forName("UTF-8"))
@ -74,8 +73,7 @@ public class WebClientController {
} }
private WebClient createWebClientWithServerURLAndDefaultValues() { private WebClient createWebClientWithServerURLAndDefaultValues() {
return WebClient return WebClient.builder()
.builder()
.baseUrl("http://localhost:8081") .baseUrl("http://localhost:8081")
.defaultCookie("cookieKey", "cookieValue") .defaultCookie("cookieKey", "cookieValue")
.defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)

View File

@ -9,14 +9,14 @@ public class ParallelIntegrationTest {
@Test @Test
public void runTests() { public void runTests() {
final Class<?>[] classes = {Example1IntegrationTest.class, Example2IntegrationTest.class}; final Class<?>[] classes = { Example1IntegrationTest.class, Example2IntegrationTest.class };
JUnitCore.runClasses(new Computer(), classes); JUnitCore.runClasses(new Computer(), classes);
} }
@Test @Test
public void runTestsInParallel() { public void runTestsInParallel() {
final Class<?>[] classes = {Example1IntegrationTest.class, Example2IntegrationTest.class}; final Class<?>[] classes = { Example1IntegrationTest.class, Example2IntegrationTest.class };
JUnitCore.runClasses(new ParallelComputer(true, true), classes); JUnitCore.runClasses(new ParallelComputer(true, true), classes);
} }

View File

@ -50,5 +50,3 @@ public class Spring5JUnit4ConcurrentIntegrationTest implements ApplicationContex
} }
} }

View File

@ -23,8 +23,7 @@ public class FunctionalWebApplicationIntegrationTest {
@BeforeClass @BeforeClass
public static void setup() throws Exception { public static void setup() throws Exception {
server = new FunctionalWebApplication().start(); server = new FunctionalWebApplication().start();
client = WebTestClient client = WebTestClient.bindToServer()
.bindToServer()
.baseUrl("http://localhost:" + server.getPort()) .baseUrl("http://localhost:" + server.getPort())
.build(); .build();
} }
@ -36,8 +35,7 @@ public class FunctionalWebApplicationIntegrationTest {
@Test @Test
public void givenRouter_whenGetTest_thenGotHelloWorld() throws Exception { public void givenRouter_whenGetTest_thenGotHelloWorld() throws Exception {
client client.get()
.get()
.uri("/test") .uri("/test")
.exchange() .exchange()
.expectStatus() .expectStatus()
@ -48,8 +46,7 @@ public class FunctionalWebApplicationIntegrationTest {
@Test @Test
public void givenIndexFilter_whenRequestRoot_thenRewrittenToTest() throws Exception { public void givenIndexFilter_whenRequestRoot_thenRewrittenToTest() throws Exception {
client client.get()
.get()
.uri("/") .uri("/")
.exchange() .exchange()
.expectStatus() .expectStatus()
@ -64,8 +61,7 @@ public class FunctionalWebApplicationIntegrationTest {
formData.add("user", "baeldung"); formData.add("user", "baeldung");
formData.add("token", "you_know_what_to_do"); formData.add("token", "you_know_what_to_do");
client client.post()
.post()
.uri("/login") .uri("/login")
.contentType(MediaType.APPLICATION_FORM_URLENCODED) .contentType(MediaType.APPLICATION_FORM_URLENCODED)
.body(BodyInserters.fromFormData(formData)) .body(BodyInserters.fromFormData(formData))
@ -82,8 +78,7 @@ public class FunctionalWebApplicationIntegrationTest {
formData.add("user", "baeldung"); formData.add("user", "baeldung");
formData.add("token", "try_again"); formData.add("token", "try_again");
client client.post()
.post()
.uri("/login") .uri("/login")
.contentType(MediaType.APPLICATION_FORM_URLENCODED) .contentType(MediaType.APPLICATION_FORM_URLENCODED)
.body(BodyInserters.fromFormData(formData)) .body(BodyInserters.fromFormData(formData))
@ -95,8 +90,7 @@ public class FunctionalWebApplicationIntegrationTest {
@Test @Test
public void givenUploadForm_whenRequestWithMultipartData_thenSuccess() throws Exception { public void givenUploadForm_whenRequestWithMultipartData_thenSuccess() throws Exception {
Resource resource = new ClassPathResource("/baeldung-weekly.png"); Resource resource = new ClassPathResource("/baeldung-weekly.png");
client client.post()
.post()
.uri("/upload") .uri("/upload")
.contentType(MediaType.MULTIPART_FORM_DATA) .contentType(MediaType.MULTIPART_FORM_DATA)
.body(fromResource(resource)) .body(fromResource(resource))
@ -109,8 +103,7 @@ public class FunctionalWebApplicationIntegrationTest {
@Test @Test
public void givenActors_whenAddActor_thenAdded() throws Exception { public void givenActors_whenAddActor_thenAdded() throws Exception {
client client.get()
.get()
.uri("/actor") .uri("/actor")
.exchange() .exchange()
.expectStatus() .expectStatus()
@ -118,16 +111,14 @@ public class FunctionalWebApplicationIntegrationTest {
.expectBodyList(Actor.class) .expectBodyList(Actor.class)
.hasSize(2); .hasSize(2);
client client.post()
.post()
.uri("/actor") .uri("/actor")
.body(fromObject(new Actor("Clint", "Eastwood"))) .body(fromObject(new Actor("Clint", "Eastwood")))
.exchange() .exchange()
.expectStatus() .expectStatus()
.isOk(); .isOk();
client client.get()
.get()
.uri("/actor") .uri("/actor")
.exchange() .exchange()
.expectStatus() .expectStatus()
@ -138,8 +129,7 @@ public class FunctionalWebApplicationIntegrationTest {
@Test @Test
public void givenResources_whenAccess_thenGot() throws Exception { public void givenResources_whenAccess_thenGot() throws Exception {
client client.get()
.get()
.uri("/files/hello.txt") .uri("/files/hello.txt")
.exchange() .exchange()
.expectStatus() .expectStatus()

View File

@ -11,18 +11,14 @@ class Spring5JUnit5ParallelIntegrationTest {
@Test @Test
void givenTwoTestClasses_whenJUnitRunParallel_thenTheTestsExecutingParallel() { void givenTwoTestClasses_whenJUnitRunParallel_thenTheTestsExecutingParallel() {
final Class<?>[] classes = { final Class<?>[] classes = { Example1IntegrationTest.class, Example2IntegrationTest.class };
Example1IntegrationTest.class, Example2IntegrationTest.class
};
JUnitCore.runClasses(new ParallelComputer(true, true), classes); JUnitCore.runClasses(new ParallelComputer(true, true), classes);
} }
@Test @Test
void givenTwoTestClasses_whenJUnitRunParallel_thenTheTestsExecutingLinear() { void givenTwoTestClasses_whenJUnitRunParallel_thenTheTestsExecutingLinear() {
final Class<?>[] classes = { final Class<?>[] classes = { Example1IntegrationTest.class, Example2IntegrationTest.class };
Example1IntegrationTest.class, Example2IntegrationTest.class
};
JUnitCore.runClasses(new Computer(), classes); JUnitCore.runClasses(new Computer(), classes);
} }

View File

@ -16,18 +16,16 @@ class Spring5Java8NewFeaturesIntegrationTest {
} }
public class StringUtils { public class StringUtils {
FunctionalInterfaceExample<String, String> FunctionalInterfaceExample<String, String> functionLambdaString = s -> Pattern.compile(" +")
functionLambdaString = s -> Pattern.compile(" +").splitAsStream(s) .splitAsStream(s)
.map(word -> new StringBuilder(word).reverse()) .map(word -> new StringBuilder(word).reverse())
.collect(Collectors.joining(" ")); .collect(Collectors.joining(" "));
} }
@Test @Test
void givenStringUtil_whenSupplierCall_thenFunctionalInterfaceReverseString() void givenStringUtil_whenSupplierCall_thenFunctionalInterfaceReverseString() throws Exception {
throws Exception {
Supplier<StringUtils> stringUtilsSupplier = StringUtils::new; Supplier<StringUtils> stringUtilsSupplier = StringUtils::new;
assertEquals(stringUtilsSupplier.get().functionLambdaString assertEquals(stringUtilsSupplier.get().functionLambdaString.reverseString("hello"), "olleh");
.reverseString("hello"), "olleh");
} }
} }

View File

@ -25,19 +25,14 @@ public class Spring5ReactiveServerClientIntegrationTest {
@BeforeAll @BeforeAll
public static void setUp() throws Exception { public static void setUp() throws Exception {
HttpServer server = HttpServer.create("localhost", 8080); HttpServer server = HttpServer.create("localhost", 8080);
RouterFunction<?> route = RouterFunctions RouterFunction<?> route = RouterFunctions.route(POST("/task/process"), request -> ServerResponse.ok()
.route(POST("/task/process"), request -> ServerResponse .body(request.bodyToFlux(Task.class)
.ok()
.body(request
.bodyToFlux(Task.class)
.map(ll -> new Task("TaskName", 1)), Task.class)) .map(ll -> new Task("TaskName", 1)), Task.class))
.and(RouterFunctions.route(GET("/task"), request -> ServerResponse .and(RouterFunctions.route(GET("/task"), request -> ServerResponse.ok()
.ok()
.body(Mono.just("server is alive"), String.class))); .body(Mono.just("server is alive"), String.class)));
HttpHandler httpHandler = RouterFunctions.toHttpHandler(route); HttpHandler httpHandler = RouterFunctions.toHttpHandler(route);
ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(httpHandler); ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(httpHandler);
nettyContext = server nettyContext = server.newHandler(adapter)
.newHandler(adapter)
.block(); .block();
} }
@ -46,53 +41,52 @@ public class Spring5ReactiveServerClientIntegrationTest {
nettyContext.dispose(); nettyContext.dispose();
} }
// @Test // @Test
// public void givenCheckTask_whenServerHandle_thenServerResponseALiveString() throws Exception { // public void givenCheckTask_whenServerHandle_thenServerResponseALiveString() throws Exception {
// WebClient client = WebClient.create("http://localhost:8080"); // WebClient client = WebClient.create("http://localhost:8080");
// Mono<String> result = client // Mono<String> result = client
// .get() // .get()
// .uri("/task") // .uri("/task")
// .exchange() // .exchange()
// .then(response -> response.bodyToMono(String.class)); // .then(response -> response.bodyToMono(String.class));
// //
// assertThat(result.block()).isInstanceOf(String.class); // assertThat(result.block()).isInstanceOf(String.class);
// } // }
// @Test // @Test
// public void givenThreeTasks_whenServerHandleTheTasks_thenServerResponseATask() throws Exception { // public void givenThreeTasks_whenServerHandleTheTasks_thenServerResponseATask() throws Exception {
// URI uri = URI.create("http://localhost:8080/task/process"); // URI uri = URI.create("http://localhost:8080/task/process");
// ExchangeFunction exchange = ExchangeFunctions.create(new ReactorClientHttpConnector()); // ExchangeFunction exchange = ExchangeFunctions.create(new ReactorClientHttpConnector());
// ClientRequest request = ClientRequest // ClientRequest request = ClientRequest
// .method(HttpMethod.POST, uri) // .method(HttpMethod.POST, uri)
// .body(BodyInserters.fromPublisher(getLatLngs(), Task.class)) // .body(BodyInserters.fromPublisher(getLatLngs(), Task.class))
// .build(); // .build();
// //
// Flux<Task> taskResponse = exchange // Flux<Task> taskResponse = exchange
// .exchange(request) // .exchange(request)
// .flatMap(response -> response.bodyToFlux(Task.class)); // .flatMap(response -> response.bodyToFlux(Task.class));
// //
// assertThat(taskResponse.blockFirst()).isInstanceOf(Task.class); // assertThat(taskResponse.blockFirst()).isInstanceOf(Task.class);
// } // }
// @Test // @Test
// public void givenCheckTask_whenServerHandle_thenOragicServerResponseALiveString() throws Exception { // public void givenCheckTask_whenServerHandle_thenOragicServerResponseALiveString() throws Exception {
// URI uri = URI.create("http://localhost:8080/task"); // URI uri = URI.create("http://localhost:8080/task");
// ExchangeFunction exchange = ExchangeFunctions.create(new ReactorClientHttpConnector()); // ExchangeFunction exchange = ExchangeFunctions.create(new ReactorClientHttpConnector());
// ClientRequest request = ClientRequest // ClientRequest request = ClientRequest
// .method(HttpMethod.GET, uri) // .method(HttpMethod.GET, uri)
// .body(BodyInserters.fromPublisher(getLatLngs(), Task.class)) // .body(BodyInserters.fromPublisher(getLatLngs(), Task.class))
// .build(); // .build();
// //
// Flux<String> taskResponse = exchange // Flux<String> taskResponse = exchange
// .exchange(request) // .exchange(request)
// .flatMap(response -> response.bodyToFlux(String.class)); // .flatMap(response -> response.bodyToFlux(String.class));
// //
// assertThat(taskResponse.blockFirst()).isInstanceOf(String.class); // assertThat(taskResponse.blockFirst()).isInstanceOf(String.class);
// } // }
private static Flux<Task> getLatLngs() { private static Flux<Task> getLatLngs() {
return Flux return Flux.range(0, 3)
.range(0, 3)
.zipWith(Flux.interval(Duration.ofSeconds(1))) .zipWith(Flux.interval(Duration.ofSeconds(1)))
.map(x -> new Task("taskname", 1)) .map(x -> new Task("taskname", 1))
.doOnNext(ll -> System.out.println("Produced: {}" + ll)); .doOnNext(ll -> System.out.println("Produced: {}" + ll));

View File

@ -21,37 +21,39 @@ public class WebTestClientTest {
@LocalServerPort @LocalServerPort
private int port; private int port;
private final RouterFunction ROUTER_FUNCTION = RouterFunctions.route( private final RouterFunction ROUTER_FUNCTION = RouterFunctions.route(RequestPredicates.GET("/resource"), request -> ServerResponse.ok()
RequestPredicates.GET("/resource"), .build());
request -> ServerResponse.ok().build()
);
private final WebHandler WEB_HANDLER = exchange -> Mono.empty(); private final WebHandler WEB_HANDLER = exchange -> Mono.empty();
@Test @Test
public void testWebTestClientWithServerWebHandler() { public void testWebTestClientWithServerWebHandler() {
WebTestClient.bindToWebHandler(WEB_HANDLER).build(); WebTestClient.bindToWebHandler(WEB_HANDLER)
.build();
} }
@Test @Test
public void testWebTestClientWithRouterFunction() { public void testWebTestClientWithRouterFunction() {
WebTestClient WebTestClient.bindToRouterFunction(ROUTER_FUNCTION)
.bindToRouterFunction(ROUTER_FUNCTION) .build()
.build().get().uri("/resource") .get()
.uri("/resource")
.exchange() .exchange()
.expectStatus().isOk() .expectStatus()
.expectBody().isEmpty(); .isOk()
.expectBody()
.isEmpty();
} }
@Test @Test
public void testWebTestClientWithServerURL() { public void testWebTestClientWithServerURL() {
WebTestClient WebTestClient.bindToServer()
.bindToServer()
.baseUrl("http://localhost:" + port) .baseUrl("http://localhost:" + port)
.build() .build()
.get() .get()
.uri("/resource") .uri("/resource")
.exchange() .exchange()
.expectStatus().is4xxClientError() .expectStatus()
.is4xxClientError()
.expectBody(); .expectBody();
} }