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";
@Test
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());
}
@Test
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());
}
@ -32,21 +35,22 @@ public class LiveTest {
final Response response = givenAuth("user", "pass").get(APP_ROOT + "/foos");
assertEquals(200, response.getStatusCode());
}*/
//
private final String resourceWithNullName() {
return "{\"name\":null}";
}
private final String resourceString() {
return "{\"name\":\"" + randomAlphabetic(8) + "\"}";
}
}
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;
@SpringBootApplication
@ComponentScan(basePackages = {"com.baeldung.web"})
@ComponentScan(basePackages = { "com.baeldung.web" })
public class Spring5Application {
public static void main(String[] args) {

View File

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

View File

@ -40,28 +40,25 @@ public class FunctionalSpringBootApplication {
private RouterFunction<ServerResponse> routingFunction() {
FormHandler formHandler = new FormHandler();
RouterFunction<ServerResponse> restfulRouter = route(GET("/"), serverRequest -> ok().body(Flux.fromIterable(actors), Actor.class)).andRoute(POST("/"), serverRequest -> serverRequest
.bodyToMono(Actor.class)
.doOnNext(actors::add)
.then(ok().build()));
RouterFunction<ServerResponse> restfulRouter = route(GET("/"), serverRequest -> ok().body(Flux.fromIterable(actors), Actor.class)).andRoute(POST("/"), serverRequest -> serverRequest.bodyToMono(Actor.class)
.doOnNext(actors::add)
.then(ok().build()));
return route(GET("/test"), serverRequest -> ok().body(fromObject("helloworld")))
.andRoute(POST("/login"), formHandler::handleLogin)
.andRoute(POST("/upload"), formHandler::handleUpload)
.and(RouterFunctions.resources("/files/**", new ClassPathResource("files/")))
.andNest(path("/actor"), restfulRouter)
.filter((request, next) -> {
System.out.println("Before handler invocation: " + request.path());
return next.handle(request);
});
return route(GET("/test"), serverRequest -> ok().body(fromObject("helloworld"))).andRoute(POST("/login"), formHandler::handleLogin)
.andRoute(POST("/upload"), formHandler::handleUpload)
.and(RouterFunctions.resources("/files/**", new ClassPathResource("files/")))
.andNest(path("/actor"), restfulRouter)
.filter((request, next) -> {
System.out.println("Before handler invocation: " + request.path());
return next.handle(request);
});
}
@Bean
public ServletRegistrationBean servletRegistrationBean() throws Exception {
HttpHandler httpHandler = WebHttpHandlerBuilder
.webHandler((WebHandler) toHttpHandler(routingFunction()))
.prependFilter(new IndexRewriteFilter())
.build();
HttpHandler httpHandler = WebHttpHandlerBuilder.webHandler((WebHandler) toHttpHandler(routingFunction()))
.prependFilter(new IndexRewriteFilter())
.build();
ServletRegistrationBean registrationBean = new ServletRegistrationBean<>(new RootServlet(httpHandler), "/");
registrationBean.setLoadOnStartup(1);
registrationBean.setAsyncSupported(true);
@ -74,10 +71,9 @@ public class FunctionalSpringBootApplication {
static class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(final HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest()
.permitAll();
http.authorizeRequests()
.anyRequest()
.permitAll();
}
}

View File

@ -33,28 +33,25 @@ public class FunctionalWebApplication {
private RouterFunction<ServerResponse> routingFunction() {
FormHandler formHandler = new FormHandler();
RouterFunction<ServerResponse> restfulRouter = route(GET("/"), serverRequest -> ok().body(Flux.fromIterable(actors), Actor.class)).andRoute(POST("/"), serverRequest -> serverRequest
.bodyToMono(Actor.class)
.doOnNext(actors::add)
.then(ok().build()));
RouterFunction<ServerResponse> restfulRouter = route(GET("/"), serverRequest -> ok().body(Flux.fromIterable(actors), Actor.class)).andRoute(POST("/"), serverRequest -> serverRequest.bodyToMono(Actor.class)
.doOnNext(actors::add)
.then(ok().build()));
return route(GET("/test"), serverRequest -> ok().body(fromObject("helloworld")))
.andRoute(POST("/login"), formHandler::handleLogin)
.andRoute(POST("/upload"), formHandler::handleUpload)
.and(RouterFunctions.resources("/files/**", new ClassPathResource("files/")))
.andNest(path("/actor"), restfulRouter)
.filter((request, next) -> {
System.out.println("Before handler invocation: " + request.path());
return next.handle(request);
});
return route(GET("/test"), serverRequest -> ok().body(fromObject("helloworld"))).andRoute(POST("/login"), formHandler::handleLogin)
.andRoute(POST("/upload"), formHandler::handleUpload)
.and(RouterFunctions.resources("/files/**", new ClassPathResource("files/")))
.andNest(path("/actor"), restfulRouter)
.filter((request, next) -> {
System.out.println("Before handler invocation: " + request.path());
return next.handle(request);
});
}
WebServer start() throws Exception {
WebHandler webHandler = (WebHandler) toHttpHandler(routingFunction());
HttpHandler httpHandler = WebHttpHandlerBuilder
.webHandler(webHandler)
.prependFilter(new IndexRewriteFilter())
.build();
HttpHandler httpHandler = WebHttpHandlerBuilder.webHandler(webHandler)
.prependFilter(new IndexRewriteFilter())
.build();
Tomcat tomcat = new Tomcat();
tomcat.setHostname("localhost");

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -20,7 +20,8 @@ public class DataSetupBean implements InitializingBean {
@Override
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
@Validated
public Foo findById(@PathVariable @Min(0) final long id) {
return repo.findById(id).orElse(null);
return repo.findById(id)
.orElse(null);
}
@GetMapping
@ -36,7 +37,8 @@ public class FooController {
@ResponseBody
@Validated
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

View File

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

View File

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

View File

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

View File

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

View File

@ -23,10 +23,9 @@ public class FunctionalWebApplicationIntegrationTest {
@BeforeClass
public static void setup() throws Exception {
server = new FunctionalWebApplication().start();
client = WebTestClient
.bindToServer()
.baseUrl("http://localhost:" + server.getPort())
.build();
client = WebTestClient.bindToServer()
.baseUrl("http://localhost:" + server.getPort())
.build();
}
@AfterClass
@ -36,26 +35,24 @@ public class FunctionalWebApplicationIntegrationTest {
@Test
public void givenRouter_whenGetTest_thenGotHelloWorld() throws Exception {
client
.get()
.uri("/test")
.exchange()
.expectStatus()
.isOk()
.expectBody(String.class)
.isEqualTo("helloworld");
client.get()
.uri("/test")
.exchange()
.expectStatus()
.isOk()
.expectBody(String.class)
.isEqualTo("helloworld");
}
@Test
public void givenIndexFilter_whenRequestRoot_thenRewrittenToTest() throws Exception {
client
.get()
.uri("/")
.exchange()
.expectStatus()
.isOk()
.expectBody(String.class)
.isEqualTo("helloworld");
client.get()
.uri("/")
.exchange()
.expectStatus()
.isOk()
.expectBody(String.class)
.isEqualTo("helloworld");
}
@Test
@ -64,16 +61,15 @@ public class FunctionalWebApplicationIntegrationTest {
formData.add("user", "baeldung");
formData.add("token", "you_know_what_to_do");
client
.post()
.uri("/login")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.body(BodyInserters.fromFormData(formData))
.exchange()
.expectStatus()
.isOk()
.expectBody(String.class)
.isEqualTo("welcome back!");
client.post()
.uri("/login")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.body(BodyInserters.fromFormData(formData))
.exchange()
.expectStatus()
.isOk()
.expectBody(String.class)
.isEqualTo("welcome back!");
}
@Test
@ -82,70 +78,64 @@ public class FunctionalWebApplicationIntegrationTest {
formData.add("user", "baeldung");
formData.add("token", "try_again");
client
.post()
.uri("/login")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.body(BodyInserters.fromFormData(formData))
.exchange()
.expectStatus()
.isBadRequest();
client.post()
.uri("/login")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.body(BodyInserters.fromFormData(formData))
.exchange()
.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)
.body(fromResource(resource))
.exchange()
.expectStatus()
.isOk()
.expectBody(String.class)
.isEqualTo(String.valueOf(resource.contentLength()));
client.post()
.uri("/upload")
.contentType(MediaType.MULTIPART_FORM_DATA)
.body(fromResource(resource))
.exchange()
.expectStatus()
.isOk()
.expectBody(String.class)
.isEqualTo(String.valueOf(resource.contentLength()));
}
@Test
public void givenActors_whenAddActor_thenAdded() throws Exception {
client
.get()
.uri("/actor")
.exchange()
.expectStatus()
.isOk()
.expectBodyList(Actor.class)
.hasSize(2);
client.get()
.uri("/actor")
.exchange()
.expectStatus()
.isOk()
.expectBodyList(Actor.class)
.hasSize(2);
client
.post()
.uri("/actor")
.body(fromObject(new Actor("Clint", "Eastwood")))
.exchange()
.expectStatus()
.isOk();
client.post()
.uri("/actor")
.body(fromObject(new Actor("Clint", "Eastwood")))
.exchange()
.expectStatus()
.isOk();
client
.get()
.uri("/actor")
.exchange()
.expectStatus()
.isOk()
.expectBodyList(Actor.class)
.hasSize(3);
client.get()
.uri("/actor")
.exchange()
.expectStatus()
.isOk()
.expectBodyList(Actor.class)
.hasSize(3);
}
@Test
public void givenResources_whenAccess_thenGot() throws Exception {
client
.get()
.uri("/files/hello.txt")
.exchange()
.expectStatus()
.isOk()
.expectBody(String.class)
.isEqualTo("hello");
client.get()
.uri("/files/hello.txt")
.exchange()
.expectStatus()
.isOk()
.expectBody(String.class)
.isEqualTo("hello");
}
}

View File

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

View File

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

View File

@ -25,20 +25,15 @@ public class Spring5ReactiveServerClientIntegrationTest {
@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)));
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();
nettyContext = server.newHandler(adapter)
.block();
}
@AfterAll
@ -46,55 +41,54 @@ public class Spring5ReactiveServerClientIntegrationTest {
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 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 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);
// }
// @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));
return Flux.range(0, 3)
.zipWith(Flux.interval(Duration.ofSeconds(1)))
.map(x -> new Task("taskname", 1))
.doOnNext(ll -> System.out.println("Produced: {}" + ll));
}
}

View File

@ -17,85 +17,85 @@ public class PathPatternsUsingHandlerMethodIntegrationTest {
@BeforeClass
public static void setUp() {
client = WebTestClient.bindToController(new PathPatternController())
.build();
.build();
}
@Test
public void givenHandlerMethod_whenMultipleURIVariablePattern_then200() {
client.get()
.uri("/spring5/ab/cd")
.exchange()
.expectStatus()
.is2xxSuccessful()
.expectBody()
.equals("/ab/cd");
.uri("/spring5/ab/cd")
.exchange()
.expectStatus()
.is2xxSuccessful()
.expectBody()
.equals("/ab/cd");
}
@Test
public void givenHandlerMethod_whenURLWithWildcardTakingZeroOrMoreChar_then200() {
client.get()
.uri("/spring5/userid")
.exchange()
.expectStatus()
.is2xxSuccessful()
.expectBody()
.equals("/spring5/*id");
.uri("/spring5/userid")
.exchange()
.expectStatus()
.is2xxSuccessful()
.expectBody()
.equals("/spring5/*id");
}
@Test
public void givenHandlerMethod_whenURLWithWildcardTakingExactlyOneChar_then200() {
client.get()
.uri("/string5")
.exchange()
.expectStatus()
.is2xxSuccessful()
.expectBody()
.equals("/s?ring5");
.uri("/string5")
.exchange()
.expectStatus()
.is2xxSuccessful()
.expectBody()
.equals("/s?ring5");
}
@Test
public void givenHandlerMethod_whenURLWithWildcardTakingZeroOrMorePathSegments_then200() {
client.get()
.uri("/resources/baeldung")
.exchange()
.expectStatus()
.is2xxSuccessful()
.expectBody()
.equals("/resources/**");
.uri("/resources/baeldung")
.exchange()
.expectStatus()
.is2xxSuccessful()
.expectBody()
.equals("/resources/**");
}
@Test
public void givenHandlerMethod_whenURLWithRegexInPathVariable_thenExpectedOutput() {
client.get()
.uri("/abc")
.exchange()
.expectStatus()
.is2xxSuccessful()
.expectBody()
.equals("abc");
.uri("/abc")
.exchange()
.expectStatus()
.is2xxSuccessful()
.expectBody()
.equals("abc");
client.get()
.uri("/123")
.exchange()
.expectStatus()
.is4xxClientError();
.uri("/123")
.exchange()
.expectStatus()
.is4xxClientError();
}
@Test
public void givenHandlerMethod_whenURLWithMultiplePathVariablesInSameSegment_then200() {
client.get()
.uri("/baeldung_tutorial")
.exchange()
.expectStatus()
.is2xxSuccessful()
.expectBody()
.equals("Two variables are var1=baeldung and var2=tutorial");
.uri("/baeldung_tutorial")
.exchange()
.expectStatus()
.is2xxSuccessful()
.expectBody()
.equals("Two variables are var1=baeldung and var2=tutorial");
}
}

View File

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