formatting work
This commit is contained in:
parent
75c1003451
commit
0f22f7b82a
@ -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());
|
||||
}
|
||||
|
||||
@ -33,8 +36,6 @@ public class LiveTest {
|
||||
assertEquals(200, response.getStatusCode());
|
||||
}*/
|
||||
|
||||
|
||||
|
||||
//
|
||||
|
||||
private final String resourceWithNullName() {
|
||||
@ -46,7 +47,10 @@ public class LiveTest {
|
||||
}
|
||||
|
||||
private final RequestSpecification givenAuth(String username, String password) {
|
||||
return RestAssured.given().auth().preemptive().basic(username, password);
|
||||
return RestAssured.given()
|
||||
.auth()
|
||||
.preemptive()
|
||||
.basic(username, password);
|
||||
}
|
||||
|
||||
}
|
@ -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) {
|
||||
|
@ -17,27 +17,24 @@ import static org.springframework.web.reactive.function.server.ServerResponse.ok
|
||||
public class FormHandler {
|
||||
|
||||
Mono<ServerResponse> handleLogin(ServerRequest request) {
|
||||
return request
|
||||
.body(toFormData())
|
||||
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());
|
||||
.switchIfEmpty(ServerResponse.badRequest()
|
||||
.build());
|
||||
}
|
||||
|
||||
Mono<ServerResponse> handleUpload(ServerRequest request) {
|
||||
return request
|
||||
.body(toDataBuffers())
|
||||
return request.body(toDataBuffers())
|
||||
.collectList()
|
||||
.flatMap(dataBuffers -> ok()
|
||||
.body(fromObject(extractData(dataBuffers).toString())));
|
||||
.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()
|
||||
dataBuffers.forEach(d -> atomicLong.addAndGet(d.asByteBuffer()
|
||||
.array().length));
|
||||
return atomicLong;
|
||||
}
|
||||
|
@ -40,13 +40,11 @@ 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)
|
||||
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)
|
||||
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)
|
||||
@ -58,8 +56,7 @@ public class FunctionalSpringBootApplication {
|
||||
|
||||
@Bean
|
||||
public ServletRegistrationBean servletRegistrationBean() throws Exception {
|
||||
HttpHandler httpHandler = WebHttpHandlerBuilder
|
||||
.webHandler((WebHandler) toHttpHandler(routingFunction()))
|
||||
HttpHandler httpHandler = WebHttpHandlerBuilder.webHandler((WebHandler) toHttpHandler(routingFunction()))
|
||||
.prependFilter(new IndexRewriteFilter())
|
||||
.build();
|
||||
ServletRegistrationBean registrationBean = new ServletRegistrationBean<>(new RootServlet(httpHandler), "/");
|
||||
@ -74,8 +71,7 @@ public class FunctionalSpringBootApplication {
|
||||
static class SecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
@Override
|
||||
protected void configure(final HttpSecurity http) throws Exception {
|
||||
http
|
||||
.authorizeRequests()
|
||||
http.authorizeRequests()
|
||||
.anyRequest()
|
||||
.permitAll();
|
||||
}
|
||||
|
@ -33,13 +33,11 @@ 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)
|
||||
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)
|
||||
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)
|
||||
@ -51,8 +49,7 @@ public class FunctionalWebApplication {
|
||||
|
||||
WebServer start() throws Exception {
|
||||
WebHandler webHandler = (WebHandler) toHttpHandler(routingFunction());
|
||||
HttpHandler httpHandler = WebHttpHandlerBuilder
|
||||
.webHandler(webHandler)
|
||||
HttpHandler httpHandler = WebHttpHandlerBuilder.webHandler(webHandler)
|
||||
.prependFilter(new IndexRewriteFilter())
|
||||
.build();
|
||||
|
||||
|
@ -11,15 +11,13 @@ class IndexRewriteFilter implements WebFilter {
|
||||
@Override
|
||||
public Mono<Void> filter(ServerWebExchange serverWebExchange, WebFilterChain webFilterChain) {
|
||||
ServerHttpRequest request = serverWebExchange.getRequest();
|
||||
if (request
|
||||
.getURI()
|
||||
if (request.getURI()
|
||||
.getPath()
|
||||
.equals("/")) {
|
||||
return webFilterChain.filter(serverWebExchange
|
||||
.mutate()
|
||||
.request(builder -> builder
|
||||
.method(request.getMethod())
|
||||
.contextPath(request.getPath().toString())
|
||||
return webFilterChain.filter(serverWebExchange.mutate()
|
||||
.request(builder -> builder.method(request.getMethod())
|
||||
.contextPath(request.getPath()
|
||||
.toString())
|
||||
.path("/test"))
|
||||
.build());
|
||||
}
|
||||
|
@ -4,7 +4,7 @@ import java.util.Random;
|
||||
|
||||
public class MyService {
|
||||
|
||||
public int getRandomNumber(){
|
||||
public int getRandomNumber() {
|
||||
return (new Random().nextInt(10));
|
||||
}
|
||||
|
||||
|
@ -28,8 +28,7 @@ import org.springframework.web.server.WebHandler;
|
||||
public class RootServlet extends ServletHttpHandlerAdapter {
|
||||
|
||||
public RootServlet() {
|
||||
this(WebHttpHandlerBuilder
|
||||
.webHandler((WebHandler) toHttpHandler(routingFunction()))
|
||||
this(WebHttpHandlerBuilder.webHandler((WebHandler) toHttpHandler(routingFunction()))
|
||||
.prependFilter(new IndexRewriteFilter())
|
||||
.build());
|
||||
}
|
||||
@ -44,38 +43,30 @@ 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)
|
||||
return ok().body(Mono.just("welcome back!"), String.class)
|
||||
.block();
|
||||
}
|
||||
return ServerResponse
|
||||
.badRequest()
|
||||
return ServerResponse.badRequest()
|
||||
.build()
|
||||
.block();
|
||||
}))
|
||||
.andRoute(POST("/upload"), serverRequest -> serverRequest
|
||||
.body(toDataBuffers())
|
||||
.andRoute(POST("/upload"), serverRequest -> serverRequest.body(toDataBuffers())
|
||||
.collectList()
|
||||
.map(dataBuffers -> {
|
||||
AtomicLong atomicLong = new AtomicLong(0);
|
||||
dataBuffers.forEach(d -> atomicLong.addAndGet(d
|
||||
.asByteBuffer()
|
||||
dataBuffers.forEach(d -> atomicLong.addAndGet(d.asByteBuffer()
|
||||
.array().length));
|
||||
System.out.println("data length:" + atomicLong.get());
|
||||
return ok()
|
||||
.body(fromObject(atomicLong.toString()))
|
||||
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)
|
||||
.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) -> {
|
||||
|
@ -27,15 +27,13 @@ abstract class ParameterAutowireUtils {
|
||||
|
||||
public static Object resolveDependency(Parameter parameter, Class<?> containingClass, ApplicationContext applicationContext) {
|
||||
|
||||
boolean required = findMergedAnnotation(parameter, Autowired.class)
|
||||
.map(Autowired::required)
|
||||
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()
|
||||
return applicationContext.getAutowireCapableBeanFactory()
|
||||
.resolveDependency(descriptor, null);
|
||||
}
|
||||
|
||||
|
@ -26,10 +26,8 @@ public class SpringExtension implements BeforeAllCallback, AfterAllCallback, Tes
|
||||
try {
|
||||
getTestContextManager(context).afterTestClass();
|
||||
} finally {
|
||||
context
|
||||
.getStore(namespace)
|
||||
.remove(context
|
||||
.getTestClass()
|
||||
context.getStore(namespace)
|
||||
.remove(context.getTestClass()
|
||||
.get());
|
||||
}
|
||||
}
|
||||
@ -42,8 +40,7 @@ public class SpringExtension implements BeforeAllCallback, AfterAllCallback, Tes
|
||||
@Override
|
||||
public void beforeEach(TestExtensionContext context) throws Exception {
|
||||
Object testInstance = context.getTestInstance();
|
||||
Method testMethod = context
|
||||
.getTestMethod()
|
||||
Method testMethod = context.getTestMethod()
|
||||
.get();
|
||||
getTestContextManager(context).beforeTestMethod(testInstance, testMethod);
|
||||
}
|
||||
@ -51,11 +48,9 @@ public class SpringExtension implements BeforeAllCallback, AfterAllCallback, Tes
|
||||
@Override
|
||||
public void afterEach(TestExtensionContext context) throws Exception {
|
||||
Object testInstance = context.getTestInstance();
|
||||
Method testMethod = context
|
||||
.getTestMethod()
|
||||
Method testMethod = context.getTestMethod()
|
||||
.get();
|
||||
Throwable testException = context
|
||||
.getTestException()
|
||||
Throwable testException = context.getTestException()
|
||||
.orElse(null);
|
||||
getTestContextManager(context).afterTestMethod(testInstance, testMethod, testException);
|
||||
}
|
||||
@ -70,23 +65,20 @@ public class SpringExtension implements BeforeAllCallback, AfterAllCallback, Tes
|
||||
@Override
|
||||
public Object resolve(ParameterContext parameterContext, ExtensionContext extensionContext) {
|
||||
Parameter parameter = parameterContext.getParameter();
|
||||
Class<?> testClass = extensionContext
|
||||
.getTestClass()
|
||||
Class<?> testClass = extensionContext.getTestClass()
|
||||
.get();
|
||||
ApplicationContext applicationContext = getApplicationContext(extensionContext);
|
||||
return ParameterAutowireUtils.resolveDependency(parameter, testClass, applicationContext);
|
||||
}
|
||||
|
||||
private ApplicationContext getApplicationContext(ExtensionContext context) {
|
||||
return getTestContextManager(context)
|
||||
.getTestContext()
|
||||
return getTestContextManager(context).getTestContext()
|
||||
.getApplicationContext();
|
||||
}
|
||||
|
||||
private TestContextManager getTestContextManager(ExtensionContext context) {
|
||||
Assert.notNull(context, "ExtensionContext must not be null");
|
||||
Class<?> testClass = context
|
||||
.getTestClass()
|
||||
Class<?> testClass = context.getTestClass()
|
||||
.get();
|
||||
ExtensionContext.Store store = context.getStore(namespace);
|
||||
return store.getOrComputeIfAbsent(testClass, TestContextManager::new, TestContextManager.class);
|
||||
|
@ -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;
|
||||
|
@ -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))));
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -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
|
||||
|
@ -23,9 +23,6 @@ public class Task {
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Task{" +
|
||||
"name='" + name + '\'' +
|
||||
", id=" + id +
|
||||
'}';
|
||||
return "Task{" + "name='" + name + '\'' + ", id=" + id + '}';
|
||||
}
|
||||
}
|
||||
|
@ -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,8 +53,7 @@ public class WebClientController {
|
||||
BodyInserter<String, ReactiveHttpOutputMessage> inserter3 = BodyInserters.fromObject("body");
|
||||
|
||||
// responses
|
||||
WebClient.ResponseSpec response1 = uri1
|
||||
.body(inserter3)
|
||||
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"))
|
||||
@ -74,8 +73,7 @@ public class WebClientController {
|
||||
}
|
||||
|
||||
private WebClient createWebClientWithServerURLAndDefaultValues() {
|
||||
return WebClient
|
||||
.builder()
|
||||
return WebClient.builder()
|
||||
.baseUrl("http://localhost:8081")
|
||||
.defaultCookie("cookieKey", "cookieValue")
|
||||
.defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
|
||||
|
@ -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);
|
||||
}
|
||||
|
@ -50,5 +50,3 @@ public class Spring5JUnit4ConcurrentIntegrationTest implements ApplicationContex
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
@ -23,8 +23,7 @@ public class FunctionalWebApplicationIntegrationTest {
|
||||
@BeforeClass
|
||||
public static void setup() throws Exception {
|
||||
server = new FunctionalWebApplication().start();
|
||||
client = WebTestClient
|
||||
.bindToServer()
|
||||
client = WebTestClient.bindToServer()
|
||||
.baseUrl("http://localhost:" + server.getPort())
|
||||
.build();
|
||||
}
|
||||
@ -36,8 +35,7 @@ public class FunctionalWebApplicationIntegrationTest {
|
||||
|
||||
@Test
|
||||
public void givenRouter_whenGetTest_thenGotHelloWorld() throws Exception {
|
||||
client
|
||||
.get()
|
||||
client.get()
|
||||
.uri("/test")
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
@ -48,8 +46,7 @@ public class FunctionalWebApplicationIntegrationTest {
|
||||
|
||||
@Test
|
||||
public void givenIndexFilter_whenRequestRoot_thenRewrittenToTest() throws Exception {
|
||||
client
|
||||
.get()
|
||||
client.get()
|
||||
.uri("/")
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
@ -64,8 +61,7 @@ public class FunctionalWebApplicationIntegrationTest {
|
||||
formData.add("user", "baeldung");
|
||||
formData.add("token", "you_know_what_to_do");
|
||||
|
||||
client
|
||||
.post()
|
||||
client.post()
|
||||
.uri("/login")
|
||||
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
|
||||
.body(BodyInserters.fromFormData(formData))
|
||||
@ -82,8 +78,7 @@ public class FunctionalWebApplicationIntegrationTest {
|
||||
formData.add("user", "baeldung");
|
||||
formData.add("token", "try_again");
|
||||
|
||||
client
|
||||
.post()
|
||||
client.post()
|
||||
.uri("/login")
|
||||
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
|
||||
.body(BodyInserters.fromFormData(formData))
|
||||
@ -95,8 +90,7 @@ public class FunctionalWebApplicationIntegrationTest {
|
||||
@Test
|
||||
public void givenUploadForm_whenRequestWithMultipartData_thenSuccess() throws Exception {
|
||||
Resource resource = new ClassPathResource("/baeldung-weekly.png");
|
||||
client
|
||||
.post()
|
||||
client.post()
|
||||
.uri("/upload")
|
||||
.contentType(MediaType.MULTIPART_FORM_DATA)
|
||||
.body(fromResource(resource))
|
||||
@ -109,8 +103,7 @@ public class FunctionalWebApplicationIntegrationTest {
|
||||
|
||||
@Test
|
||||
public void givenActors_whenAddActor_thenAdded() throws Exception {
|
||||
client
|
||||
.get()
|
||||
client.get()
|
||||
.uri("/actor")
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
@ -118,16 +111,14 @@ public class FunctionalWebApplicationIntegrationTest {
|
||||
.expectBodyList(Actor.class)
|
||||
.hasSize(2);
|
||||
|
||||
client
|
||||
.post()
|
||||
client.post()
|
||||
.uri("/actor")
|
||||
.body(fromObject(new Actor("Clint", "Eastwood")))
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk();
|
||||
|
||||
client
|
||||
.get()
|
||||
client.get()
|
||||
.uri("/actor")
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
@ -138,8 +129,7 @@ public class FunctionalWebApplicationIntegrationTest {
|
||||
|
||||
@Test
|
||||
public void givenResources_whenAccess_thenGot() throws Exception {
|
||||
client
|
||||
.get()
|
||||
client.get()
|
||||
.uri("/files/hello.txt")
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
|
@ -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);
|
||||
}
|
||||
|
@ -16,18 +16,16 @@ class Spring5Java8NewFeaturesIntegrationTest {
|
||||
}
|
||||
|
||||
public class StringUtils {
|
||||
FunctionalInterfaceExample<String, String>
|
||||
functionLambdaString = s -> Pattern.compile(" +").splitAsStream(s)
|
||||
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");
|
||||
}
|
||||
}
|
||||
|
@ -25,19 +25,14 @@ 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)
|
||||
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()
|
||||
.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)
|
||||
nettyContext = server.newHandler(adapter)
|
||||
.block();
|
||||
}
|
||||
|
||||
@ -46,53 +41,52 @@ 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)
|
||||
return Flux.range(0, 3)
|
||||
.zipWith(Flux.interval(Duration.ofSeconds(1)))
|
||||
.map(x -> new Task("taskname", 1))
|
||||
.doOnNext(ll -> System.out.println("Produced: {}" + ll));
|
||||
|
@ -21,37 +21,39 @@ 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")
|
||||
WebTestClient.bindToRouterFunction(ROUTER_FUNCTION)
|
||||
.build()
|
||||
.get()
|
||||
.uri("/resource")
|
||||
.exchange()
|
||||
.expectStatus().isOk()
|
||||
.expectBody().isEmpty();
|
||||
.expectStatus()
|
||||
.isOk()
|
||||
.expectBody()
|
||||
.isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testWebTestClientWithServerURL() {
|
||||
WebTestClient
|
||||
.bindToServer()
|
||||
WebTestClient.bindToServer()
|
||||
.baseUrl("http://localhost:" + port)
|
||||
.build()
|
||||
.get()
|
||||
.uri("/resource")
|
||||
.exchange()
|
||||
.expectStatus().is4xxClientError()
|
||||
.expectStatus()
|
||||
.is4xxClientError()
|
||||
.expectBody();
|
||||
}
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user