From abaecd4af5c99213be70aa8ee535879d80557384 Mon Sep 17 00:00:00 2001 From: "H. Habighorst" Date: Sat, 3 Jun 2023 18:05:07 +0200 Subject: [PATCH 01/15] Migrate from JUnit 4 to JUnit 5 --- .../caffeine/NamedCaffeineCacheSpec.java | 20 +- .../guice/GuiceApplicationBuilderTest.java | 25 +- .../guice/GuiceApplicationLoaderTest.java | 16 +- .../guice/GuiceInjectorBuilderTest.java | 124 +++--- .../BuiltInComponentsFromContextTest.java | 86 ++-- .../play/it/JavaServerIntegrationTest.java | 25 +- .../play/routing/AbstractRoutingDslTest.java | 126 +++--- .../CompileTimeInjectionRoutingDslTest.java | 4 +- .../DependencyInjectedRoutingDslTest.java | 8 +- .../test/java/play/libs/ResourcesTest.java | 16 +- .../src/test/java/play/libs/TimeTest.java | 24 +- .../test/java/play/mvc/AttributesTest.java | 68 +-- .../src/test/java/play/mvc/HttpTest.java | 80 ++-- .../java/play/mvc/RequestBuilderTest.java | 19 +- .../java/play/mvc/ResultAttributesTest.java | 65 ++- .../play/libs/streams/AccumulatorTest.java | 10 +- .../src/test/java/play/core/PathsTest.java | 4 +- .../src/test/java/play/i18n/MessagesTest.java | 6 +- .../play/libs/concurrent/FuturesTest.java | 29 +- .../play/src/test/java/play/mvc/CallTest.java | 4 +- .../test/java/play/mvc/CookieBuilderTest.java | 4 +- .../test/java/play/mvc/RangeResultsTest.java | 19 +- .../src/test/java/play/mvc/ResultsTest.java | 19 +- .../src/test/java/play/mvc/SecurityTest.java | 4 +- .../working/javaGuide/main/tests/JavaTest.md | 4 +- .../src/test/java/play/db/DatabaseTest.java | 78 ++-- .../test/java/play/db/NamedDatabaseTest.java | 107 +++-- .../src/test/java/play/db/jpa/JPAApiTest.java | 104 +++-- .../play/db/evolutions/EvolutionsTest.java | 22 +- project/BuildSettings.scala | 3 +- project/Dependencies.scala | 16 +- project/plugins.sbt | 1 + .../src/test/java/play/test/HelpersTest.java | 55 ++- .../test/java/play/test/TestServerTest.java | 28 +- .../src/test/java/play/mvc/HttpFormsTest.java | 391 +++++++++--------- .../play/data/format/FormattersTest.java | 8 +- 36 files changed, 802 insertions(+), 820 deletions(-) diff --git a/cache/play-caffeine-cache/src/test/java/play/cache/caffeine/NamedCaffeineCacheSpec.java b/cache/play-caffeine-cache/src/test/java/play/cache/caffeine/NamedCaffeineCacheSpec.java index daaf7de3767..c2433f493cc 100644 --- a/cache/play-caffeine-cache/src/test/java/play/cache/caffeine/NamedCaffeineCacheSpec.java +++ b/cache/play-caffeine-cache/src/test/java/play/cache/caffeine/NamedCaffeineCacheSpec.java @@ -4,14 +4,14 @@ package play.cache.caffeine; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.core.IsEqual.equalTo; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import com.github.benmanes.caffeine.cache.Caffeine; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.slf4j.LoggerFactory; public class NamedCaffeineCacheSpec { @@ -37,7 +37,7 @@ public void getAll_shouldReturnAllValuesWithTheGivenKeys() throws Exception { expectedMap.put(key1, value1); expectedMap.put(key2, value2); - assertThat(resultMap, equalTo(expectedMap)); + assertEquals(expectedMap, resultMap); } @Test @@ -59,7 +59,7 @@ public void getAll_shouldCreateTheMissingValuesAndReturnAllWithTheGivenKeys() th expectedMap.put(key1, value1); expectedMap.put(key2, value2); - assertThat(resultMap, equalTo(expectedMap)); + assertEquals(expectedMap, resultMap); } @Test @@ -82,18 +82,18 @@ public void getAll_shouldNotReplaceAlreadyExistingValues() throws Exception { expectedMap.put(key1, value1); expectedMap.put(key2, value2); - assertThat(resultMap, equalTo(expectedMap)); + assertEquals(expectedMap, resultMap); } @Test() - public void getAll_shouldReturnFailedFutureIfMappingFunctionIsCompletedExceptionally() - throws Exception { + public void getAll_shouldReturnFailedFutureIfMappingFunctionIsCompletedExceptionally() { LoggerFactory.getLogger(NamedCaffeineCache.class); RuntimeException testException = new RuntimeException("test exception"); CompletableFuture> future = new CompletableFuture<>(); future.completeExceptionally(testException); CompletableFuture> resultFuture = - cache.getAll(new HashSet<>(Arrays.asList("key1")), (missingKeys, executor) -> future); - assertThat(resultFuture.isCompletedExceptionally(), equalTo(true)); + cache.getAll(new HashSet<>(List.of("key1")), (missingKeys, executor) -> future); + + assertTrue(resultFuture.isCompletedExceptionally()); } } diff --git a/core/play-guice/src/test/java/play/inject/guice/GuiceApplicationBuilderTest.java b/core/play-guice/src/test/java/play/inject/guice/GuiceApplicationBuilderTest.java index 42cf6602b86..e7cfa725cf8 100644 --- a/core/play-guice/src/test/java/play/inject/guice/GuiceApplicationBuilderTest.java +++ b/core/play-guice/src/test/java/play/inject/guice/GuiceApplicationBuilderTest.java @@ -4,10 +4,7 @@ package play.inject.guice; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertThrows; +import static org.junit.jupiter.api.Assertions.*; import static play.inject.Bindings.bind; import com.google.common.collect.ImmutableList; @@ -17,7 +14,7 @@ import com.typesafe.config.ConfigFactory; import javax.inject.Inject; import javax.inject.Provider; -import org.junit.Test; +import org.junit.jupiter.api.Test; import play.Application; import play.api.inject.guice.GuiceApplicationBuilderSpec; import play.inject.Injector; @@ -33,8 +30,8 @@ public void addBindings() { .bindings(bind(B.class).to(B1.class)) .injector(); - assertThat(injector.instanceOf(A.class), instanceOf(A1.class)); - assertThat(injector.instanceOf(B.class), instanceOf(B1.class)); + assertInstanceOf(A1.class, injector.instanceOf(A.class)); + assertInstanceOf(B1.class, injector.instanceOf(B.class)); } @Test @@ -56,16 +53,16 @@ public void overrideBindings() { .injector() .instanceOf(Application.class); - assertThat(app.config().getInt("a"), is(1)); - assertThat(app.config().getInt("b"), is(2)); - assertThat(app.injector().instanceOf(A.class), instanceOf(A2.class)); + assertEquals(1, app.config().getInt("a")); + assertEquals(2, app.config().getInt("b")); + assertInstanceOf(A2.class, app.injector().instanceOf(A.class)); } @Test public void disableModules() { Injector injector = new GuiceApplicationBuilder().bindings(new AModule()).disable(AModule.class).injector(); - assertThrows(ConfigurationException.class, () -> injector.instanceOf(A.class)); + assertThrowsExactly(ConfigurationException.class, () -> injector.instanceOf(A.class)); } @Test @@ -76,7 +73,7 @@ public void setInitialConfigurationLoader() { .withConfigLoader(env -> extra.withFallback(ConfigFactory.load(env.classLoader()))) .build(); - assertThat(app.config().getInt("a"), is(1)); + assertEquals(1, app.config().getInt("a")); } @Test @@ -93,7 +90,7 @@ public void setModuleLoader() { Guiceable.bindings(bind(A.class).to(A1.class)))) .injector(); - assertThat(injector.instanceOf(A.class), instanceOf(A1.class)); + assertInstanceOf(A1.class, injector.instanceOf(A.class)); } @Test @@ -108,7 +105,7 @@ public void setLoadedModulesDirectly() { Guiceable.bindings(bind(A.class).to(A1.class))) .injector(); - assertThat(injector.instanceOf(A.class), instanceOf(A1.class)); + assertInstanceOf(A1.class, injector.instanceOf(A.class)); } public static interface A {} diff --git a/core/play-guice/src/test/java/play/inject/guice/GuiceApplicationLoaderTest.java b/core/play-guice/src/test/java/play/inject/guice/GuiceApplicationLoaderTest.java index 45845fa984a..2d58ae83884 100644 --- a/core/play-guice/src/test/java/play/inject/guice/GuiceApplicationLoaderTest.java +++ b/core/play-guice/src/test/java/play/inject/guice/GuiceApplicationLoaderTest.java @@ -4,16 +4,14 @@ package play.inject.guice; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static play.inject.Bindings.bind; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import java.util.Properties; -import org.junit.Test; +import org.junit.jupiter.api.Test; import play.Application; import play.ApplicationLoader; import play.Environment; @@ -31,8 +29,8 @@ public void additionalModulesAndBindings() { ApplicationLoader loader = new GuiceApplicationLoader(builder); Application app = loader.load(fakeContext()); - assertThat(app.injector().instanceOf(A.class), instanceOf(A1.class)); - assertThat(app.injector().instanceOf(B.class), instanceOf(B1.class)); + assertInstanceOf(A1.class, app.injector().instanceOf(A.class)); + assertInstanceOf(B1.class, app.injector().instanceOf(B.class)); } @Test @@ -50,7 +48,7 @@ public GuiceApplicationBuilder builder(Context context) { }; Application app = loader.load(fakeContext()); - assertThat(app.config().getInt("a"), is(1)); + assertEquals(1, app.config().getInt("a")); } @Test @@ -67,7 +65,7 @@ public void usingAdditionalConfiguration() { ApplicationLoader.create(Environment.simple()).withConfig(config); Application app = loader.load(context); - assertThat(app.asScala().httpConfiguration().context(), equalTo("/tests")); + assertEquals("/tests", app.asScala().httpConfiguration().context()); } public interface A {} diff --git a/core/play-guice/src/test/java/play/inject/guice/GuiceInjectorBuilderTest.java b/core/play-guice/src/test/java/play/inject/guice/GuiceInjectorBuilderTest.java index 7d9a7159ed8..fd8966ff8f7 100644 --- a/core/play-guice/src/test/java/play/inject/guice/GuiceInjectorBuilderTest.java +++ b/core/play-guice/src/test/java/play/inject/guice/GuiceInjectorBuilderTest.java @@ -4,9 +4,9 @@ package play.inject.guice; -import static org.hamcrest.CoreMatchers.*; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertThrows; +import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Named.named; +import static org.junit.jupiter.params.provider.Arguments.arguments; import static play.inject.Bindings.bind; import com.google.common.collect.ImmutableMap; @@ -18,7 +18,11 @@ import java.net.URLClassLoader; import java.util.Collections; import java.util.List; -import org.junit.Test; +import java.util.stream.Stream; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import play.Environment; import play.Mode; import play.inject.Binding; @@ -28,17 +32,15 @@ public class GuiceInjectorBuilderTest { - @Test - public void setEnvironmentWithScala() { - setEnvironment(new EnvironmentModule()); + static Stream environmentTargets() { + return Stream.of( + arguments(named("Scala Env", new EnvironmentModule())), + arguments(named("Java Env", new JavaEnvironmentModule()))); } - @Test - public void setEnvironmentWithJava() { - setEnvironment(new JavaEnvironmentModule()); - } - - private void setEnvironment(play.api.inject.Module environmentModule) { + @ParameterizedTest + @MethodSource("environmentTargets") + void setEnvironment(play.api.inject.Module environmentModule) { ClassLoader classLoader = new URLClassLoader(new URL[0]); Environment env = new GuiceInjectorBuilder() @@ -47,22 +49,14 @@ private void setEnvironment(play.api.inject.Module environmentModule) { .injector() .instanceOf(Environment.class); - assertThat(env.rootPath(), equalTo(new File("test"))); - assertThat(env.mode(), equalTo(Mode.DEV)); - assertThat(env.classLoader(), sameInstance(classLoader)); - } - - @Test - public void setEnvironmentValuesWithScala() { - setEnvironmentValues(new EnvironmentModule()); - } - - @Test - public void setEnvironmentValuesWithJava() { - setEnvironmentValues(new JavaEnvironmentModule()); + assertEquals(new File("test"), env.rootPath()); + assertEquals(Mode.DEV, env.mode()); + assertInstanceOf(classLoader.getClass(), env.classLoader()); } - private void setEnvironmentValues(play.api.inject.Module environmentModule) { + @ParameterizedTest + @MethodSource("environmentTargets") + void setEnvironmentValues(play.api.inject.Module environmentModule) { ClassLoader classLoader = new URLClassLoader(new URL[0]); Environment env = new GuiceInjectorBuilder() @@ -73,22 +67,20 @@ private void setEnvironmentValues(play.api.inject.Module environmentModule) { .injector() .instanceOf(Environment.class); - assertThat(env.rootPath(), equalTo(new File("test"))); - assertThat(env.mode(), equalTo(Mode.DEV)); - assertThat(env.classLoader(), sameInstance(classLoader)); + assertEquals(new File("test"), env.rootPath()); + assertEquals(Mode.DEV, env.mode()); + assertInstanceOf(classLoader.getClass(), env.classLoader()); } - @Test - public void setConfigurationWithScala() { - setConfiguration(new ConfigurationModule()); - } - - @Test - public void setConfigurationWithJava() { - setConfiguration(new JavaConfigurationModule()); + static Stream configurationTargets() { + return Stream.of( + arguments(named("Java", new JavaConfigurationModule())), + arguments(named("Scala", new ConfigurationModule()))); } - private void setConfiguration(play.api.inject.Module configurationModule) { + @ParameterizedTest + @MethodSource("configurationTargets") + void setConfiguration(play.api.inject.Module configurationModule) { Config conf = new GuiceInjectorBuilder() .configure(ConfigFactory.parseMap(ImmutableMap.of("a", 1))) @@ -100,27 +92,29 @@ private void setConfiguration(play.api.inject.Module configurationModule) { .injector() .instanceOf(Config.class); - assertThat(conf.root().keySet().size(), is(4)); - assertThat(conf.root().keySet(), hasItems("a", "b", "c", "d")); + assertEquals(4, conf.root().keySet().size()); + assertTrue(conf.root().keySet().containsAll(List.of("a", "b", "c", "d"))); - assertThat(conf.getInt("a"), is(1)); - assertThat(conf.getInt("b"), is(2)); - assertThat(conf.getInt("c"), is(3)); - assertThat(conf.getInt("d.1"), is(4)); - assertThat(conf.getInt("d.2"), is(5)); + assertEquals(1, conf.getInt("a")); + assertEquals(2, conf.getInt("b")); + assertEquals(3, conf.getInt("c")); + assertEquals(4, conf.getInt("d.1")); + assertEquals(5, conf.getInt("d.2")); } - @Test - public void supportVariousBindingsWithScala() { - supportVariousBindings(new EnvironmentModule(), new ConfigurationModule()); - } - - @Test - public void supportVariousBindingsWithJava() { - supportVariousBindings(new JavaEnvironmentModule(), new JavaConfigurationModule()); + static Stream bindingTargets() { + return Stream.of( + arguments( + named("Scala Env", new EnvironmentModule()), + named("Scala Config", new ConfigurationModule())), + arguments( + named("Java Env", new JavaEnvironmentModule()), + named("Java Config", new JavaConfigurationModule()))); } - private void supportVariousBindings( + @ParameterizedTest + @MethodSource("bindingTargets") + void supportVariousBindings( play.api.inject.Module environmentModule, play.api.inject.Module configurationModule) { Injector injector = new GuiceInjectorBuilder() @@ -129,12 +123,12 @@ private void supportVariousBindings( .bindings(bind(C.class).to(C1.class), bind(D.class).toInstance(new D1())) .injector(); - assertThat(injector.instanceOf(Environment.class), instanceOf(Environment.class)); - assertThat(injector.instanceOf(Config.class), instanceOf(Config.class)); - assertThat(injector.instanceOf(A.class), instanceOf(A1.class)); - assertThat(injector.instanceOf(B.class), instanceOf(B1.class)); - assertThat(injector.instanceOf(C.class), instanceOf(C1.class)); - assertThat(injector.instanceOf(D.class), instanceOf(D1.class)); + assertInstanceOf(Environment.class, injector.instanceOf(Environment.class)); + assertInstanceOf(Config.class, injector.instanceOf(Config.class)); + assertInstanceOf(A1.class, injector.instanceOf(A.class)); + assertInstanceOf(B1.class, injector.instanceOf(B.class)); + assertInstanceOf(C1.class, injector.instanceOf(C.class)); + assertInstanceOf(D1.class, injector.instanceOf(D.class)); } @Test @@ -147,8 +141,8 @@ public void overrideBindings() { .overrides(bind(B.class).to(B2.class)) .injector(); - assertThat(injector.instanceOf(A.class), instanceOf(A2.class)); - assertThat(injector.instanceOf(B.class), instanceOf(B2.class)); + assertInstanceOf(A2.class, injector.instanceOf(A.class)); + assertInstanceOf(B2.class, injector.instanceOf(B.class)); } @Test @@ -160,8 +154,8 @@ public void disableModules() { .disable(AModule.class, CModule.class) // C won't be disabled .injector(); - assertThat(injector.instanceOf(B.class), instanceOf(B1.class)); - assertThat(injector.instanceOf(C.class), instanceOf(C1.class)); + assertInstanceOf(B1.class, injector.instanceOf(B.class)); + assertInstanceOf(C1.class, injector.instanceOf(C.class)); assertThrows(ConfigurationException.class, () -> injector.instanceOf(A.class)); } diff --git a/core/play-integration-test/src/it/java/play/BuiltInComponentsFromContextTest.java b/core/play-integration-test/src/it/java/play/BuiltInComponentsFromContextTest.java index 29a0e7f65cc..feae0d64e08 100644 --- a/core/play-integration-test/src/it/java/play/BuiltInComponentsFromContextTest.java +++ b/core/play-integration-test/src/it/java/play/BuiltInComponentsFromContextTest.java @@ -4,14 +4,11 @@ package play; -import static org.hamcrest.CoreMatchers.*; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; import java.io.File; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import play.api.http.HttpConfiguration; import play.api.mvc.RequestHeader; import play.components.BodyParserComponents; @@ -46,7 +43,7 @@ public Router router() { private BuiltInComponentsFromContext componentsFromContext; - @Before + @BeforeEach public void initialize() { ApplicationLoader.Context context = ApplicationLoader.create(Environment.simple()); this.componentsFromContext = new TestBuiltInComponentsFromContext(context); @@ -60,154 +57,145 @@ public void shouldProvideAApplication() { () -> { Http.RequestBuilder request = Helpers.fakeRequest(Helpers.GET, "/"); Result result = Helpers.route(application, request); - assertThat(result.status(), equalTo(Helpers.OK)); + assertEquals(Helpers.OK, result.status()); }); } @Test public void shouldProvideDefaultFilters() { - assertThat(this.componentsFromContext.httpFilters().isEmpty(), is(false)); + assertFalse(this.componentsFromContext.httpFilters().isEmpty()); } @Test public void shouldProvideRouter() { Router router = this.componentsFromContext.router(); - assertThat(router, notNullValue()); + assertNotNull(router); Http.RequestHeader ok = Helpers.fakeRequest(Helpers.GET, "/").build(); - assertThat(router.route(ok).isPresent(), is(true)); + assertTrue(router.route(ok).isPresent()); Http.RequestHeader notFound = Helpers.fakeRequest(Helpers.GET, "/404").build(); - assertThat(router.route(notFound).isPresent(), is(false)); + assertFalse(router.route(notFound).isPresent()); } @Test public void shouldProvideHttpConfiguration() { HttpConfiguration httpConfiguration = this.componentsFromContext.httpConfiguration(); - assertThat(httpConfiguration.context(), equalTo("/")); - assertThat(httpConfiguration, notNullValue()); + assertNotNull(httpConfiguration); + assertEquals("/", httpConfiguration.context()); } // The tests below just ensure that the we are able to instantiate the components @Test public void shouldProvideApplicationLifecycle() { - assertThat(this.componentsFromContext.applicationLifecycle(), notNullValue()); + assertNotNull(this.componentsFromContext.applicationLifecycle()); } @Test public void shouldProvideActionCreator() { - assertThat(this.componentsFromContext.actionCreator(), notNullValue()); + assertNotNull(this.componentsFromContext.actionCreator()); } @Test public void shouldProvideAkkActorSystem() { - assertThat(this.componentsFromContext.actorSystem(), notNullValue()); + assertNotNull(this.componentsFromContext.actorSystem()); } @Test public void shouldProvideAkkaMaterializer() { - assertThat(this.componentsFromContext.materializer(), notNullValue()); + assertNotNull(this.componentsFromContext.materializer()); } @Test public void shouldProvideExecutionContext() { - assertThat(this.componentsFromContext.executionContext(), notNullValue()); + assertNotNull(this.componentsFromContext.executionContext()); } @Test public void shouldProvideCookieSigner() { - assertThat(this.componentsFromContext.cookieSigner(), notNullValue()); + assertNotNull(this.componentsFromContext.cookieSigner()); } @Test public void shouldProvideCSRFTokenSigner() { - assertThat(this.componentsFromContext.csrfTokenSigner(), notNullValue()); + assertNotNull(this.componentsFromContext.csrfTokenSigner()); } @Test public void shouldProvideFileMimeTypes() { - assertThat(this.componentsFromContext.fileMimeTypes(), notNullValue()); + assertNotNull(this.componentsFromContext.fileMimeTypes()); } @Test public void shouldProvideHttpErrorHandler() { - assertThat(this.componentsFromContext.httpErrorHandler(), notNullValue()); + assertNotNull(this.componentsFromContext.httpErrorHandler()); } @Test public void shouldProvideHttpRequestHandler() { - assertThat(this.componentsFromContext.httpRequestHandler(), notNullValue()); + assertNotNull(this.componentsFromContext.httpRequestHandler()); } @Test public void shouldProvideLangs() { - assertThat(this.componentsFromContext.langs(), notNullValue()); + assertNotNull(this.componentsFromContext.langs()); } @Test public void shouldProvideMessagesApi() { - assertThat(this.componentsFromContext.messagesApi(), notNullValue()); + assertNotNull(this.componentsFromContext.messagesApi()); } @Test public void shouldProvideTempFileCreator() { - assertThat(this.componentsFromContext.tempFileCreator(), notNullValue()); + assertNotNull(this.componentsFromContext.tempFileCreator()); } @Test public void actorSystemMustBeASingleton() { - assertThat( - this.componentsFromContext.actorSystem(), - sameInstance(this.componentsFromContext.actorSystem())); + assertSame(this.componentsFromContext.actorSystem(), this.componentsFromContext.actorSystem()); } @Test public void applicationMustBeASingleton() { - assertThat( - this.componentsFromContext.application(), - sameInstance(this.componentsFromContext.application())); + assertSame(this.componentsFromContext.application(), this.componentsFromContext.application()); } @Test public void langsMustBeASingleton() { - assertThat( - this.componentsFromContext.langs(), sameInstance(this.componentsFromContext.langs())); + assertSame(this.componentsFromContext.langs(), this.componentsFromContext.langs()); } @Test public void fileMimeTypesMustBeASingleton() { - assertThat( - this.componentsFromContext.fileMimeTypes(), - sameInstance(this.componentsFromContext.fileMimeTypes())); + assertSame( + this.componentsFromContext.fileMimeTypes(), this.componentsFromContext.fileMimeTypes()); } @Test public void httpRequestHandlerMustBeASingleton() { - assertThat( + assertSame( this.componentsFromContext.httpRequestHandler(), - sameInstance(this.componentsFromContext.httpRequestHandler())); + this.componentsFromContext.httpRequestHandler()); } @Test public void cookieSignerMustBeASingleton() { - assertThat( - this.componentsFromContext.cookieSigner(), - sameInstance(this.componentsFromContext.cookieSigner())); + assertSame( + this.componentsFromContext.cookieSigner(), this.componentsFromContext.cookieSigner()); } @Test public void csrfTokenSignerMustBeASingleton() { - assertThat( - this.componentsFromContext.csrfTokenSigner(), - sameInstance(this.componentsFromContext.csrfTokenSigner())); + assertSame( + this.componentsFromContext.csrfTokenSigner(), this.componentsFromContext.csrfTokenSigner()); } @Test public void temporaryFileCreatorMustBeASingleton() { - assertThat( - this.componentsFromContext.tempFileCreator(), - sameInstance(this.componentsFromContext.tempFileCreator())); + assertSame( + this.componentsFromContext.tempFileCreator(), this.componentsFromContext.tempFileCreator()); } @Test diff --git a/core/play-integration-test/src/it/java/play/it/JavaServerIntegrationTest.java b/core/play-integration-test/src/it/java/play/it/JavaServerIntegrationTest.java index 91d6eee24e9..ad877e55ab0 100644 --- a/core/play-integration-test/src/it/java/play/it/JavaServerIntegrationTest.java +++ b/core/play-integration-test/src/it/java/play/it/JavaServerIntegrationTest.java @@ -4,7 +4,7 @@ package play.it; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import java.io.IOException; import java.io.InputStream; @@ -17,7 +17,7 @@ import javax.net.ssl.SSLHandshakeException; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; -import org.junit.Test; +import org.junit.jupiter.api.Test; import play.routing.Router; import play.server.Server; @@ -31,12 +31,11 @@ public void testHttpEmbeddedServerUsesCorrectProtocolAndPort() throws Exception assertTrue(_isPortOccupied(port)); assertFalse(_isServingSSL(port)); assertEquals(server.httpPort(), port); - try { - server.httpsPort(); - fail( - "Exception should be thrown on accessing https port of server that is not serving that protocol"); - } catch (IllegalStateException e) { - } + + assertThrowsExactly( + IllegalStateException.class, + () -> server.httpsPort(), + "Exception should be thrown on accessing https port of server that is not serving that protocol"); }); assertFalse(_isPortOccupied(port)); } @@ -50,12 +49,10 @@ public void testHttpsEmbeddedServerUsesCorrectProtocolAndPort() throws Exception assertEquals(server.httpsPort(), port); assertTrue(_isServingSSL(port)); - try { - server.httpPort(); - fail( - "Exception should be thrown on accessing http port of server that is not serving that protocol"); - } catch (IllegalStateException e) { - } + assertThrowsExactly( + IllegalStateException.class, + () -> server.httpPort(), + "Exception should be thrown on accessing http port of server that is not serving that protocol"); }); assertFalse(_isPortOccupied(port)); } diff --git a/core/play-integration-test/src/it/java/play/routing/AbstractRoutingDslTest.java b/core/play-integration-test/src/it/java/play/routing/AbstractRoutingDslTest.java index 7170d6d15b5..e947199faf5 100644 --- a/core/play-integration-test/src/it/java/play/routing/AbstractRoutingDslTest.java +++ b/core/play-integration-test/src/it/java/play/routing/AbstractRoutingDslTest.java @@ -5,9 +5,7 @@ package play.routing; import static java.util.concurrent.CompletableFuture.completedFuture; -import static org.hamcrest.CoreMatchers.*; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.*; import static play.mvc.Results.internalServerError; import static play.mvc.Results.ok; import static play.test.Helpers.*; @@ -20,7 +18,7 @@ import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.function.Function; -import org.junit.Test; +import org.junit.jupiter.api.Test; import play.Application; import play.libs.Files; import play.libs.Json; @@ -58,7 +56,7 @@ public void shouldProvideJavaRequestToActionWithoutParameters() { String result = makeRequest(router, "GET", "/with-request", rb -> rb.header("X-Test", "Header value")); - assertThat(result, equalTo("Header value")); + assertEquals("Header value", result); } @Test @@ -78,7 +76,7 @@ public void shouldProvideJavaRequestToActionWithSingleParameter() { String result = makeRequest(router, "GET", "/with-request/10", rb -> rb.header("X-Test", "Header value")); - assertThat(result, equalTo("Header value - 10")); + assertEquals("Header value - 10", result); } @Test @@ -99,7 +97,7 @@ public void shouldProvideJavaRequestToActionWith2Parameters() { String result = makeRequest( router, "GET", "/with-request/10/20", rb -> rb.header("X-Test", "Header value")); - assertThat(result, equalTo("Header value - 10 - 20")); + assertEquals("Header value - 10 - 20", result); } @Test @@ -122,7 +120,7 @@ public void shouldProvideJavaRequestToActionWith3Parameters() { String result = makeRequest( router, "GET", "/with-request/10/20/30", rb -> rb.header("X-Test", "Header value")); - assertThat(result, equalTo("Header value - 10 - 20 - 30")); + assertEquals("Header value - 10 - 20 - 30", result); } @Test @@ -143,7 +141,7 @@ public void shouldProvideJavaRequestToAsyncActionWithoutParameters() { String result = makeRequest(router, "GET", "/with-request", rb -> rb.header("X-Test", "Header value")); - assertThat(result, equalTo("Header value")); + assertEquals("Header value", result); } @Test @@ -164,7 +162,7 @@ public void shouldProvideJavaRequestToAsyncActionWithSingleParameter() { String result = makeRequest(router, "GET", "/with-request/10", rb -> rb.header("X-Test", "Header value")); - assertThat(result, equalTo("Header value - 10")); + assertEquals("Header value - 10", result); } @Test @@ -186,7 +184,7 @@ public void shouldProvideJavaRequestToAsyncActionWith2Parameters() { String result = makeRequest( router, "GET", "/with-request/10/20", rb -> rb.header("X-Test", "Header value")); - assertThat(result, equalTo("Header value - 10 - 20")); + assertEquals("Header value - 10 - 20", result); } @Test @@ -211,7 +209,7 @@ public void shouldProvideJavaRequestToAsyncActionWith3Parameters() { String result = makeRequest( router, "GET", "/with-request/10/20/30", rb -> rb.header("X-Test", "Header value")); - assertThat(result, equalTo("Header value - 10 - 20 - 30")); + assertEquals("Header value - 10 - 20 - 30", result); } @Test @@ -225,7 +223,7 @@ public void shouldPreserveRequestBodyAsText() { .build()); String result = makeRequest(router, "POST", "/with-body", rb -> rb.bodyText("The Body")); - assertThat(result, equalTo("The Body")); + assertEquals("The Body", result); } @Test @@ -244,7 +242,7 @@ public void shouldPreserveRequestBodyAsJson() { "POST", "/with-body", requestBuilder -> requestBuilder.bodyJson(Json.parse("{ \"a\": \"b\" }"))); - assertThat(result, equalTo("{\"a\":\"b\"}")); + assertEquals("{\"a\":\"b\"}", result); } @Test @@ -265,7 +263,7 @@ public void shouldPreserveRequestBodyAsXml() { requestBuilder -> requestBuilder.bodyXml( XML.fromString("b"))); - assertThat(result, equalTo("b")); + assertEquals("b", result); } @Test @@ -284,7 +282,7 @@ public void shouldPreserveRequestBodyAsRawBuffer() { "POST", "/with-body", requestBuilder -> requestBuilder.bodyRaw(ByteString.fromString("The Raw Body"))); - assertThat(result, equalTo("The Raw Body")); + assertEquals("The Raw Body", result); } @Test @@ -335,13 +333,12 @@ public void shouldAcceptMultipartFormData() throws IOException { List.of( new Http.MultipartFormData.FilePart<>( "document", "jabberwocky.txt", "text/plain", tempFile)))); - assertThat( - result, - equalTo( - "author: Lewis Carrol\n" - + "filename: jabberwocky.txt\n" - + "contentType: text/plain\n" - + "contents: Twas brillig and the slithy Toves...\n")); + assertEquals( + "author: Lewis Carrol\n" + + "filename: jabberwocky.txt\n" + + "contentType: text/plain\n" + + "contents: Twas brillig and the slithy Toves...\n", + result); } @Test @@ -352,7 +349,7 @@ public void shouldPreserveRequestBodyAsTextWhenUsingHttpRequest() { routingDsl.POST("/with-body").routingTo(req -> ok(req.body().asText())).build()); String result = makeRequest(router, "POST", "/with-body", rb -> rb.bodyText("The Body")); - assertThat(result, equalTo("The Body")); + assertEquals("The Body", result); } @Test @@ -368,7 +365,7 @@ public void shouldPreserveRequestBodyAsJsonWhenUsingHttpRequest() { "POST", "/with-body", requestBuilder -> requestBuilder.bodyJson(Json.parse("{ \"a\": \"b\" }"))); - assertThat(result, equalTo("{\"a\":\"b\"}")); + assertEquals("{\"a\":\"b\"}", result); } @Test @@ -389,7 +386,7 @@ public void shouldPreserveRequestBodyAsXmlWhenUsingHttpRequest() { requestBuilder -> requestBuilder.bodyXml( XML.fromString("b"))); - assertThat(result, equalTo("b")); + assertEquals("b", result); } @Test @@ -408,7 +405,7 @@ public void shouldPreserveRequestBodyAsRawBufferWhenUsingHttpRequest() { "POST", "/with-body", requestBuilder -> requestBuilder.bodyRaw(ByteString.fromString("The Raw Body"))); - assertThat(result, equalTo("The Raw Body")); + assertEquals("The Raw Body", result); } @Test @@ -418,7 +415,7 @@ public void noParameters() { routingDsl -> routingDsl.GET("/hello/world").routingTo(req -> ok("Hello world")).build()); - assertThat(makeRequest(router, "GET", "/hello/world"), equalTo("Hello world")); + assertEquals("Hello world", makeRequest(router, "GET", "/hello/world")); assertNull(makeRequest(router, "GET", "/foo/bar")); } @@ -429,7 +426,7 @@ public void oneParameter() { routingDsl -> routingDsl.GET("/hello/:to").routingTo((req, to) -> ok("Hello " + to)).build()); - assertThat(makeRequest(router, "GET", "/hello/world"), equalTo("Hello world")); + assertEquals("Hello world", makeRequest(router, "GET", "/hello/world")); assertNull(makeRequest(router, "GET", "/foo/bar")); } @@ -443,7 +440,7 @@ public void twoParameters() { .routingTo((req, say, to) -> ok(say + " " + to)) .build()); - assertThat(makeRequest(router, "GET", "/Hello/world"), equalTo("Hello world")); + assertEquals("Hello world", makeRequest(router, "GET", "/Hello/world")); assertNull(makeRequest(router, "GET", "/foo")); } @@ -457,7 +454,7 @@ public void threeParameters() { .routingTo((req, say, to, extra) -> ok(say + " " + to + extra)) .build()); - assertThat(makeRequest(router, "GET", "/Hello/world/!"), equalTo("Hello world!")); + assertEquals("Hello world!", makeRequest(router, "GET", "/Hello/world/!")); assertNull(makeRequest(router, "GET", "/foo/bar")); } @@ -471,7 +468,7 @@ public void noParametersAsync() { .routingAsync(req -> completedFuture(ok("Hello world"))) .build()); - assertThat(makeRequest(router, "GET", "/hello/world"), equalTo("Hello world")); + assertEquals("Hello world", makeRequest(router, "GET", "/hello/world")); assertNull(makeRequest(router, "GET", "/foo/bar")); } @@ -485,7 +482,7 @@ public void oneParameterAsync() { .routingAsync((req, to) -> completedFuture(ok("Hello " + to))) .build()); - assertThat(makeRequest(router, "GET", "/hello/world"), equalTo("Hello world")); + assertEquals("Hello world", makeRequest(router, "GET", "/hello/world")); assertNull(makeRequest(router, "GET", "/foo/bar")); } @@ -499,7 +496,7 @@ public void twoParametersAsync() { .routingAsync((req, say, to) -> completedFuture(ok(say + " " + to))) .build()); - assertThat(makeRequest(router, "GET", "/Hello/world"), equalTo("Hello world")); + assertEquals("Hello world", makeRequest(router, "GET", "/Hello/world")); assertNull(makeRequest(router, "GET", "/foo")); } @@ -514,7 +511,7 @@ public void threeParametersAsync() { (req, say, to, extra) -> completedFuture(ok(say + " " + to + extra))) .build()); - assertThat(makeRequest(router, "GET", "/Hello/world/!"), equalTo("Hello world!")); + assertEquals("Hello world!", makeRequest(router, "GET", "/Hello/world/!")); assertNull(makeRequest(router, "GET", "/foo/bar")); } @@ -525,7 +522,7 @@ public void get() { routingDsl -> routingDsl.GET("/hello/world").routingTo(req -> ok("Hello world")).build()); - assertThat(makeRequest(router, "GET", "/hello/world"), equalTo("Hello world")); + assertEquals("Hello world", makeRequest(router, "GET", "/hello/world")); assertNull(makeRequest(router, "POST", "/hello/world")); } @@ -536,7 +533,7 @@ public void head() { routingDsl -> routingDsl.HEAD("/hello/world").routingTo(req -> ok("Hello world")).build()); - assertThat(makeRequest(router, "HEAD", "/hello/world"), equalTo("Hello world")); + assertEquals("Hello world", makeRequest(router, "HEAD", "/hello/world")); assertNull(makeRequest(router, "POST", "/hello/world")); } @@ -547,7 +544,7 @@ public void post() { routingDsl -> routingDsl.POST("/hello/world").routingTo(req -> ok("Hello world")).build()); - assertThat(makeRequest(router, "POST", "/hello/world"), equalTo("Hello world")); + assertEquals("Hello world", makeRequest(router, "POST", "/hello/world")); assertNull(makeRequest(router, "GET", "/hello/world")); } @@ -558,7 +555,7 @@ public void put() { routingDsl -> routingDsl.PUT("/hello/world").routingTo(req -> ok("Hello world")).build()); - assertThat(makeRequest(router, "PUT", "/hello/world"), equalTo("Hello world")); + assertEquals("Hello world", makeRequest(router, "PUT", "/hello/world")); assertNull(makeRequest(router, "POST", "/hello/world")); } @@ -569,7 +566,7 @@ public void delete() { routingDsl -> routingDsl.DELETE("/hello/world").routingTo(req -> ok("Hello world")).build()); - assertThat(makeRequest(router, "DELETE", "/hello/world"), equalTo("Hello world")); + assertEquals("Hello world", makeRequest(router, "DELETE", "/hello/world")); assertNull(makeRequest(router, "POST", "/hello/world")); } @@ -580,7 +577,7 @@ public void patch() { routingDsl -> routingDsl.PATCH("/hello/world").routingTo(req -> ok("Hello world")).build()); - assertThat(makeRequest(router, "PATCH", "/hello/world"), equalTo("Hello world")); + assertEquals("Hello world", makeRequest(router, "PATCH", "/hello/world")); assertNull(makeRequest(router, "POST", "/hello/world")); } @@ -591,7 +588,7 @@ public void options() { routingDsl -> routingDsl.OPTIONS("/hello/world").routingTo(req -> ok("Hello world")).build()); - assertThat(makeRequest(router, "OPTIONS", "/hello/world"), equalTo("Hello world")); + assertEquals("Hello world", makeRequest(router, "OPTIONS", "/hello/world")); assertNull(makeRequest(router, "POST", "/hello/world")); } @@ -610,8 +607,8 @@ public void withSessionAndHeader() { .build()); Result result = routeAndCall(application(), router, fakeRequest("GET", "/hello/world")); - assertThat(result.session().get("foo"), equalTo(Optional.of("bar"))); - assertThat(result.headers().get("Foo"), equalTo("Bar")); + assertEquals(Optional.of("bar"), result.session().get("foo")); + assertEquals("Bar", result.headers().get("Foo")); } @Test @@ -621,7 +618,7 @@ public void starMatcher() { routingDsl -> routingDsl.GET("/hello/*to").routingTo((req, to) -> ok("Hello " + to)).build()); - assertThat(makeRequest(router, "GET", "/hello/blah/world"), equalTo("Hello blah/world")); + assertEquals("Hello blah/world", makeRequest(router, "GET", "/hello/blah/world")); assertNull(makeRequest(router, "GET", "/foo/bar")); } @@ -635,7 +632,7 @@ public void regexMatcher() { .routingTo((req, to) -> ok("Hello " + to)) .build()); - assertThat(makeRequest(router, "GET", "/hello/world"), equalTo("Hello world")); + assertEquals("Hello world", makeRequest(router, "GET", "/hello/world")); assertNull(makeRequest(router, "GET", "/hello/10")); } @@ -655,10 +652,10 @@ public void multipleRoutes() { .routingTo((req, path) -> ok("Path " + path)) .build()); - assertThat(makeRequest(router, "GET", "/hello/world"), equalTo("Hello world")); - assertThat(makeRequest(router, "GET", "/foo/bar"), equalTo("foo bar")); - assertThat(makeRequest(router, "POST", "/hello/world"), equalTo("Post world")); - assertThat(makeRequest(router, "GET", "/something/else"), equalTo("Path something/else")); + assertEquals("Hello world", makeRequest(router, "GET", "/hello/world")); + assertEquals("foo bar", makeRequest(router, "GET", "/foo/bar")); + assertEquals("Post world", makeRequest(router, "POST", "/hello/world")); + assertEquals("Path something/else", makeRequest(router, "GET", "/something/else")); } @Test @@ -675,9 +672,9 @@ public void encoding() { .routingTo((req, to) -> ok("Regex " + to)) .build()); - assertThat(makeRequest(router, "GET", "/simple/dollar%24"), equalTo("Simple dollar$")); - assertThat(makeRequest(router, "GET", "/path/dollar%24"), equalTo("Path dollar%24")); - assertThat(makeRequest(router, "GET", "/regex/dollar%24"), equalTo("Regex dollar%24")); + assertEquals("Simple dollar$", makeRequest(router, "GET", "/simple/dollar%24")); + assertEquals("Path dollar%24", makeRequest(router, "GET", "/path/dollar%24")); + assertEquals("Regex dollar%24", makeRequest(router, "GET", "/regex/dollar%24")); } @Test @@ -692,18 +689,21 @@ public void typed() { ok("int " + a + " boolean " + b + " string " + c)) .build()); - assertThat( - makeRequest(router, "GET", "/20/true/foo"), equalTo("int 20 boolean true string foo")); + assertEquals("int 20 boolean true string foo", makeRequest(router, "GET", "/20/true/foo")); } - @Test(expected = IllegalArgumentException.class) + @Test public void wrongNumberOfParameters() { - routingDsl().GET("/:a/:b").routingTo((req, foo) -> ok(foo.toString())); + assertThrowsExactly( + IllegalArgumentException.class, + () -> routingDsl().GET("/:a/:b").routingTo((req, foo) -> ok(foo.toString()))); } - @Test(expected = IllegalArgumentException.class) + @Test public void badParameterType() { - routingDsl().GET("/:a").routingTo((Http.Request req, InputStream is) -> ok()); + assertThrowsExactly( + IllegalArgumentException.class, + () -> routingDsl().GET("/:a").routingTo((Http.Request req, InputStream is) -> ok())); } @Test @@ -716,9 +716,9 @@ public void bindError() { .routingTo((Http.Request req, Integer a) -> ok("int " + a)) .build()); - assertThat( - makeRequest(router, "GET", "/foo"), - equalTo("Cannot parse parameter a as Int: For input string: \"foo\"")); + assertEquals( + "Cannot parse parameter a as Int: For input string: \"foo\"", + makeRequest(router, "GET", "/foo")); } @Test @@ -731,7 +731,7 @@ public void customPathBindable() { .routingTo((Http.Request req, MyString myString) -> ok(myString.value)) .build()); - assertThat(makeRequest(router, "GET", "/foo"), equalTo("a:foo")); + assertEquals("a:foo", makeRequest(router, "GET", "/foo")); } public static class MyString implements PathBindable { diff --git a/core/play-integration-test/src/it/java/play/routing/CompileTimeInjectionRoutingDslTest.java b/core/play-integration-test/src/it/java/play/routing/CompileTimeInjectionRoutingDslTest.java index 4b844c77d5b..759c7e3e8fa 100644 --- a/core/play-integration-test/src/it/java/play/routing/CompileTimeInjectionRoutingDslTest.java +++ b/core/play-integration-test/src/it/java/play/routing/CompileTimeInjectionRoutingDslTest.java @@ -4,7 +4,7 @@ package play.routing; -import org.junit.BeforeClass; +import org.junit.jupiter.api.BeforeAll; import play.Application; import play.ApplicationLoader; import play.filters.components.NoHttpFiltersComponents; @@ -14,7 +14,7 @@ public class CompileTimeInjectionRoutingDslTest extends AbstractRoutingDslTest { private static TestComponents components; private static Application application; - @BeforeClass + @BeforeAll public static void startApp() { play.ApplicationLoader.Context context = play.ApplicationLoader.create(play.Environment.simple()); diff --git a/core/play-integration-test/src/it/java/play/routing/DependencyInjectedRoutingDslTest.java b/core/play-integration-test/src/it/java/play/routing/DependencyInjectedRoutingDslTest.java index 9e2ea001c4a..57d3a2a7549 100644 --- a/core/play-integration-test/src/it/java/play/routing/DependencyInjectedRoutingDslTest.java +++ b/core/play-integration-test/src/it/java/play/routing/DependencyInjectedRoutingDslTest.java @@ -4,8 +4,8 @@ package play.routing; -import org.junit.AfterClass; -import org.junit.BeforeClass; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; import play.Application; import play.inject.guice.GuiceApplicationBuilder; import play.test.Helpers; @@ -14,7 +14,7 @@ public class DependencyInjectedRoutingDslTest extends AbstractRoutingDslTest { private static Application app; - @BeforeClass + @BeforeAll public static void startApp() { app = new GuiceApplicationBuilder().configure("play.allowGlobalApplication", true).build(); Helpers.start(app); @@ -30,7 +30,7 @@ RoutingDsl routingDsl() { return app.injector().instanceOf(RoutingDsl.class); } - @AfterClass + @AfterAll public static void stopApp() { Helpers.stop(app); } diff --git a/core/play-java/src/test/java/play/libs/ResourcesTest.java b/core/play-java/src/test/java/play/libs/ResourcesTest.java index fcd77a57ffe..b7a5d5e51d0 100644 --- a/core/play-java/src/test/java/play/libs/ResourcesTest.java +++ b/core/play-java/src/test/java/play/libs/ResourcesTest.java @@ -4,13 +4,15 @@ package play.libs; +import static org.junit.jupiter.api.Assertions.assertThrowsExactly; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import java.io.InputStream; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; -import org.junit.Test; +import java.util.concurrent.ExecutionException; +import org.junit.jupiter.api.Test; public class ResourcesTest { @@ -37,12 +39,12 @@ public void testAsyncTryWithResourceExceptionInFuture() throws Exception { throw new RuntimeException("test exception"); })); - try { - completionStage.toCompletableFuture().get(); - } catch (Exception ignored) { - // print this so we can diagnose why it failed - ignored.printStackTrace(); - } + final ExecutionException exc = + assertThrowsExactly( + ExecutionException.class, () -> completionStage.toCompletableFuture().get()); + + // print this so we can diagnose why it failed + exc.printStackTrace(); verify(inputStream).close(); } diff --git a/core/play-java/src/test/java/play/libs/TimeTest.java b/core/play-java/src/test/java/play/libs/TimeTest.java index ccbf5bf1f28..a77e5cc1d7d 100644 --- a/core/play-java/src/test/java/play/libs/TimeTest.java +++ b/core/play-java/src/test/java/play/libs/TimeTest.java @@ -4,10 +4,10 @@ package play.libs; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TimeTest { @@ -33,14 +33,14 @@ public void testSeconds() { try { Time.parseDuration("1S"); - Assert.fail("Should have thrown an IllegalArgumentException"); + fail("Should have thrown an IllegalArgumentException"); } catch (IllegalArgumentException iae) { assertEquals("Invalid duration pattern : " + "1S", iae.getMessage()); } try { Time.parseDuration("100S"); - Assert.fail("Should have thrown an IllegalArgumentException"); + fail("Should have thrown an IllegalArgumentException"); } catch (IllegalArgumentException iae) { assertEquals("Invalid duration pattern : " + "100S", iae.getMessage()); } @@ -62,21 +62,21 @@ public void testMinutes() { try { Time.parseDuration("1MIN"); - Assert.fail("Should have thrown an IllegalArgumentException"); + fail("Should have thrown an IllegalArgumentException"); } catch (IllegalArgumentException iae) { assertEquals("Invalid duration pattern : " + "1MIN", iae.getMessage()); } try { Time.parseDuration("100MN"); - Assert.fail("Should have thrown an IllegalArgumentException"); + fail("Should have thrown an IllegalArgumentException"); } catch (IllegalArgumentException iae) { assertEquals("Invalid duration pattern : " + "100MN", iae.getMessage()); } try { Time.parseDuration("100mN"); - Assert.fail("Should have thrown an IllegalArgumentException"); + fail("Should have thrown an IllegalArgumentException"); } catch (IllegalArgumentException iae) { assertEquals("Invalid duration pattern : " + "100mN", iae.getMessage()); } @@ -92,14 +92,14 @@ public void testHours() { try { Time.parseDuration("1H"); - Assert.fail("Should have thrown an IllegalArgumentException"); + fail("Should have thrown an IllegalArgumentException"); } catch (IllegalArgumentException iae) { assertEquals("Invalid duration pattern : " + "1H", iae.getMessage()); } try { Time.parseDuration("100H"); - Assert.fail("Should have thrown an IllegalArgumentException"); + fail("Should have thrown an IllegalArgumentException"); } catch (IllegalArgumentException iae) { assertEquals("Invalid duration pattern : " + "100H", iae.getMessage()); } @@ -115,14 +115,14 @@ public void testDays() { try { Time.parseDuration("1D"); - Assert.fail("Should have thrown an IllegalArgumentException"); + fail("Should have thrown an IllegalArgumentException"); } catch (IllegalArgumentException iae) { assertEquals("Invalid duration pattern : " + "1D", iae.getMessage()); } try { Time.parseDuration("100D"); - Assert.fail("Should have thrown an IllegalArgumentException"); + fail("Should have thrown an IllegalArgumentException"); } catch (IllegalArgumentException iae) { assertEquals("Invalid duration pattern : " + "100D", iae.getMessage()); } diff --git a/core/play-java/src/test/java/play/mvc/AttributesTest.java b/core/play-java/src/test/java/play/mvc/AttributesTest.java index 06c0a1d69de..25f7bac3c8b 100644 --- a/core/play-java/src/test/java/play/mvc/AttributesTest.java +++ b/core/play-java/src/test/java/play/mvc/AttributesTest.java @@ -4,37 +4,31 @@ package play.mvc; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.util.Arrays; -import java.util.Collection; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Named.named; +import static org.junit.jupiter.params.provider.Arguments.arguments; + +import java.util.stream.Stream; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import play.core.j.RequestHeaderImpl; import play.libs.typedmap.TypedEntry; import play.libs.typedmap.TypedKey; -@RunWith(Parameterized.class) public final class AttributesTest { - @Parameters - public static Collection targets() { - return Arrays.asList( - new Http.RequestBuilder().build(), - new RequestHeaderImpl(new Http.RequestBuilder().build().asScala())); + static Stream targets() { + return Stream.of( + arguments(named("Java", new Http.RequestBuilder().build())), + arguments( + named("Scala", new RequestHeaderImpl(new Http.RequestBuilder().build().asScala())))); } - private Http.RequestHeader requestHeader; - - public AttributesTest(final Http.RequestHeader requestHeader) { - this.requestHeader = requestHeader; - } - - @Test - public void testRequestHeader_addSingleAttribute() { + @ParameterizedTest + @MethodSource("targets") + void testRequestHeader_addSingleAttribute(final Http.RequestHeader requestHeader) { final TypedKey color = TypedKey.create("color"); final Http.RequestHeader newRequestHeader = requestHeader.addAttr(color, "red"); @@ -43,8 +37,10 @@ public void testRequestHeader_addSingleAttribute() { assertEquals("red", newRequestHeader.attrs().get(color)); } - @Test - public void testRequestHeader_KeepCurrentAttributesWhenAddingANewOne() { + @ParameterizedTest + @MethodSource("targets") + void testRequestHeader_KeepCurrentAttributesWhenAddingANewOne( + final Http.RequestHeader requestHeader) { final TypedKey number = TypedKey.create("number"); final TypedKey color = TypedKey.create("color"); @@ -56,8 +52,9 @@ public void testRequestHeader_KeepCurrentAttributesWhenAddingANewOne() { assertEquals("red", newRequestHeader.attrs().get(color)); } - @Test - public void testRequestHeader_OverrideExistingValue() { + @ParameterizedTest + @MethodSource("targets") + void testRequestHeader_OverrideExistingValue(final Http.RequestHeader requestHeader) { final TypedKey number = TypedKey.create("number"); final TypedKey color = TypedKey.create("color"); @@ -70,8 +67,9 @@ public void testRequestHeader_OverrideExistingValue() { assertEquals("white", newRequestHeader.attrs().get(color)); } - @Test - public void testRequestHeader_addMultipleAttributes() { + @ParameterizedTest + @MethodSource("targets") + void testRequestHeader_addMultipleAttributes(final Http.RequestHeader requestHeader) { final TypedKey number = TypedKey.create("number"); final TypedKey color = TypedKey.create("color"); @@ -84,8 +82,10 @@ public void testRequestHeader_addMultipleAttributes() { assertEquals((Long) 3L, newRequestHeader.attrs().get(number)); } - @Test - public void testRequestHeader_KeepCurrentAttributesWhenAddingMultipleOnes() { + @ParameterizedTest + @MethodSource("targets") + void testRequestHeader_KeepCurrentAttributesWhenAddingMultipleOnes( + final Http.RequestHeader requestHeader) { final TypedKey number = TypedKey.create("number"); final TypedKey color = TypedKey.create("color"); final TypedKey direction = TypedKey.create("direction"); @@ -103,8 +103,10 @@ public void testRequestHeader_KeepCurrentAttributesWhenAddingMultipleOnes() { assertEquals("red", newRequestHeader.attrs().get(color)); } - @Test - public void testRequestHeader_OverrideExistingValueWhenAddingMultipleAttributes() { + @ParameterizedTest + @MethodSource("targets") + void testRequestHeader_OverrideExistingValueWhenAddingMultipleAttributes( + final Http.RequestHeader requestHeader) { final TypedKey number = TypedKey.create("number"); final TypedKey color = TypedKey.create("color"); diff --git a/core/play-java/src/test/java/play/mvc/HttpTest.java b/core/play-java/src/test/java/play/mvc/HttpTest.java index 4db1d720438..7f04831fcab 100644 --- a/core/play-java/src/test/java/play/mvc/HttpTest.java +++ b/core/play-java/src/test/java/play/mvc/HttpTest.java @@ -4,14 +4,15 @@ package play.mvc; -import static org.fest.assertions.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import static play.mvc.Http.HeaderNames.ACCEPT_LANGUAGE; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import java.util.Optional; import java.util.function.Consumer; -import org.junit.Test; +import org.junit.jupiter.api.Test; import play.Application; import play.Environment; import play.i18n.Lang; @@ -66,17 +67,17 @@ public void testChangeLang() { // Start off as 'en' with no cookie set Request req = new RequestBuilder().build(); Result result = Results.ok(); - assertThat(messagesApi(app).preferred(req).lang().code()).isEqualTo("en"); - assertThat(resultLangCookie(result, messagesApi(app))).isNull(); + assertEquals("en", messagesApi(app).preferred(req).lang().code()); + assertNull(resultLangCookie(result, messagesApi(app))); // Change the language to 'en-US' Lang lang = Lang.forCode("en-US"); req = new RequestBuilder().langCookie(lang, messagesApi(app)).build(); result = result.withLang(lang, messagesApi(app)); // The language and cookie should now be 'en-US' - assertThat(messagesApi(app).preferred(req).lang().code()).isEqualTo("en-US"); - assertThat(resultLangCookie(result, messagesApi(app))).isEqualTo("en-US"); + assertEquals("en-US", messagesApi(app).preferred(req).lang().code()); + assertEquals("en-US", resultLangCookie(result, messagesApi(app))); // The Messages instance uses the language which is set now into account - assertThat(messagesApi(app).preferred(req).at("hello")).isEqualTo("Aloha"); + assertEquals("Aloha", messagesApi(app).preferred(req).at("hello")); }); } @@ -87,18 +88,18 @@ public void testMessagesOrder() { RequestBuilder rb = new RequestBuilder().header(ACCEPT_LANGUAGE, "en-US"); Request req = rb.build(); // if no cookie is provided the lang order will have the accept language as the default - assertThat(messagesApi(app).preferred(req).lang().code()).isEqualTo("en-US"); + assertEquals("en-US", messagesApi(app).preferred(req).lang().code()); Lang fr = Lang.forCode("fr"); rb = new RequestBuilder().langCookie(fr, messagesApi(app)).header(ACCEPT_LANGUAGE, "en"); req = rb.build(); // if no transient lang is provided the language order will be cookie > accept language - assertThat(messagesApi(app).preferred(req).lang().code()).isEqualTo("fr"); + assertEquals("fr", messagesApi(app).preferred(req).lang().code()); // if a transient lang is set the order will be transient lang > cookie > accept language req = rb.build().withTransientLang(Lang.forCode("en-US")); - assertThat(messagesApi(app).preferred(req).lang().code()).isEqualTo("en-US"); + assertEquals("en-US", messagesApi(app).preferred(req).lang().code()); }); } @@ -109,15 +110,15 @@ public void testChangeLangFailure() { // Start off as 'en' with no cookie set Request req = new RequestBuilder().build(); Result result = Results.ok(); - assertThat(messagesApi(app).preferred(req).lang().code()).isEqualTo("en"); - assertThat(resultLangCookie(result, messagesApi(app))).isNull(); + assertEquals("en", messagesApi(app).preferred(req).lang().code()); + assertNull(resultLangCookie(result, messagesApi(app))); Lang lang = Lang.forCode("en-NZ"); req = new RequestBuilder().langCookie(lang, messagesApi(app)).build(); result = result.withLang(lang, messagesApi(app)); // Try to change the language to 'en-NZ' - which fails, the language should still be 'en' - assertThat(messagesApi(app).preferred(req).lang().code()).isEqualTo("en"); + assertEquals("en", messagesApi(app).preferred(req).lang().code()); // The cookie however will get set - assertThat(resultLangCookie(result, messagesApi(app))).isEqualTo("en-NZ"); + assertEquals("en-NZ", resultLangCookie(result, messagesApi(app))); }); } @@ -129,14 +130,14 @@ public void testClearLang() { Lang lang = Lang.forCode("fr"); Request req = new RequestBuilder().langCookie(lang, messagesApi(app)).build(); Result result = Results.ok().withLang(lang, messagesApi(app)); - assertThat(messagesApi(app).preferred(req).lang().code()).isEqualTo("fr"); - assertThat(resultLangCookie(result, messagesApi(app))).isEqualTo("fr"); + assertEquals("fr", messagesApi(app).preferred(req).lang().code()); + assertEquals("fr", resultLangCookie(result, messagesApi(app))); // Clear language result = result.withoutLang(messagesApi(app)); // The cookie should be cleared - assertThat(resultLangCookie(result, messagesApi(app))).isEqualTo(""); + assertEquals("", resultLangCookie(result, messagesApi(app))); // However the request is not effected by changing the result - assertThat(messagesApi(app).preferred(req).lang().code()).isEqualTo("fr"); + assertEquals("fr", messagesApi(app).preferred(req).lang().code()); }); } @@ -147,32 +148,33 @@ public void testSetTransientLang() { Request req = new RequestBuilder().build(); Result result = Results.ok(); // Start off as 'en' with no cookie set - assertThat(messagesApi(app).preferred(req).lang().code()).isEqualTo("en"); - assertThat(resultLangCookie(result, messagesApi(app))).isNull(); + assertEquals("en", messagesApi(app).preferred(req).lang().code()); + assertNull(resultLangCookie(result, messagesApi(app))); // Change the language to 'en-US' req = req.withTransientLang(Lang.forCode("en-US")); // The language should now be 'en-US', but the cookie mustn't be set - assertThat(messagesApi(app).preferred(req).lang().code()).isEqualTo("en-US"); - assertThat(resultLangCookie(result, messagesApi(app))).isNull(); + assertEquals("en-US", messagesApi(app).preferred(req).lang().code()); + assertNull(resultLangCookie(result, messagesApi(app))); // The Messages instance uses the language which is set now into account - assertThat(messagesApi(app).preferred(req).at("hello")).isEqualTo("Aloha"); + assertEquals("Aloha", messagesApi(app).preferred(req).at("hello")); }); } + @Test public void testSetTransientLangFailure() { withApplication( (app) -> { Request req = new RequestBuilder().build(); Result result = Results.ok(); // Start off as 'en' with no cookie set - assertThat(messagesApi(app).preferred(req).lang().code()).isEqualTo("en"); - assertThat(resultLangCookie(result, messagesApi(app))).isNull(); + assertEquals("en", messagesApi(app).preferred(req).lang().code()); + assertNull(resultLangCookie(result, messagesApi(app))); // Try to change the language to 'en-NZ' req = req.withTransientLang(Lang.forCode("en-NZ")); // When trying to get the messages it does not work because en-NZ is not valid - assertThat(messagesApi(app).preferred(req).lang().code()).isEqualTo("en"); + assertEquals("en", messagesApi(app).preferred(req).lang().code()); // However if you access the transient lang directly you will see it was set - assertThat(req.transientLang().map(Lang::code)).isEqualTo(Optional.of("en-NZ")); + assertEquals(Optional.of("en-NZ"), req.transientLang().map(Lang::code)); }); } @@ -185,21 +187,21 @@ public void testClearTransientLang() { Result result = Results.ok().withLang(lang, messagesApi(app)); // Start off as 'fr' with cookie set Request req = rb.build(); - assertThat(messagesApi(app).preferred(req).lang().code()).isEqualTo("fr"); - assertThat(resultLangCookie(result, messagesApi(app))).isEqualTo("fr"); + assertEquals("fr", messagesApi(app).preferred(req).lang().code()); + assertEquals("fr", resultLangCookie(result, messagesApi(app))); // Change the language to 'en-US' lang = Lang.forCode("en-US"); req = req.withTransientLang(lang); result = result.withLang(lang, messagesApi(app)); // The language should now be 'en-US' and the cookie must be set again - assertThat(messagesApi(app).preferred(req).lang().code()).isEqualTo("en-US"); - assertThat(resultLangCookie(result, messagesApi(app))).isEqualTo("en-US"); + assertEquals("en-US", messagesApi(app).preferred(req).lang().code()); + assertEquals("en-US", resultLangCookie(result, messagesApi(app))); // Clear the language to the default for the current request and result req = req.withoutTransientLang(); result = result.withoutLang(messagesApi(app)); // The language should now be back to 'fr', and the cookie must be cleared - assertThat(messagesApi(app).preferred(req).lang().code()).isEqualTo("fr"); - assertThat(resultLangCookie(result, messagesApi(app))).isEqualTo(""); + assertEquals("fr", messagesApi(app).preferred(req).lang().code()); + assertEquals("", resultLangCookie(result, messagesApi(app))); }); } @@ -214,24 +216,24 @@ public void testRequestImplLang() { req = req.withTransientLang(Lang.forCode("fr")); // Make sure the request did set that lang correctly - assertThat(messagesApi(app).preferred(req).lang().code()).isEqualTo("fr"); + assertEquals("fr", messagesApi(app).preferred(req).lang().code()); // Now let's copy the request Request newReq = new Http.RequestImpl(req.asScala()); // Make sure the new request correctly set its internal lang variable - assertThat(messagesApi(app).preferred(newReq).lang().code()).isEqualTo("fr"); + assertEquals("fr", messagesApi(app).preferred(newReq).lang().code()); // Now change the lang on the new request to something not default newReq = newReq.withTransientLang(Lang.forCode("en-US")); // Make sure the new request correctly set its internal lang variable - assertThat(messagesApi(app).preferred(newReq).lang().code()).isEqualTo("en-US"); - assertThat(newReq.transientLang().map(Lang::code)).isEqualTo(Optional.of("en-US")); + assertEquals("en-US", messagesApi(app).preferred(newReq).lang().code()); + assertEquals(Optional.of("en-US"), newReq.transientLang().map(Lang::code)); // Also make sure the original request didn't change it's language - assertThat(messagesApi(app).preferred(req).lang().code()).isEqualTo("fr"); - assertThat(req.transientLang().map(Lang::code)).isEqualTo(Optional.of("fr")); + assertEquals("fr", messagesApi(app).preferred(req).lang().code()); + assertEquals(Optional.of("fr"), req.transientLang().map(Lang::code)); }); } } diff --git a/core/play-java/src/test/java/play/mvc/RequestBuilderTest.java b/core/play-java/src/test/java/play/mvc/RequestBuilderTest.java index f933596a1d5..efd9b1ab79e 100644 --- a/core/play-java/src/test/java/play/mvc/RequestBuilderTest.java +++ b/core/play-java/src/test/java/play/mvc/RequestBuilderTest.java @@ -4,8 +4,7 @@ package play.mvc; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import akka.stream.javadsl.FileIO; import akka.stream.javadsl.Source; @@ -21,8 +20,7 @@ import java.util.Map; import java.util.Optional; import java.util.concurrent.ExecutionException; -import org.hamcrest.CoreMatchers; -import org.junit.Test; +import org.junit.jupiter.api.Test; import play.api.Application; import play.api.Play; import play.api.inject.guice.GuiceApplicationBuilder; @@ -423,12 +421,11 @@ public void multipartForm_bodyRaw_correctEscapedParams() throws URISyntaxExcepti String body = request.body().asBytes().utf8String(); // Let's get the text representation of the bytes - assertThat( - body, - CoreMatchers.containsString("Content-Disposition: form-data; name=\"f%0Ai%0De%22l%0Ad1\"")); - assertThat( - body, - CoreMatchers.containsString( + + assertNotNull(body); + assertTrue(body.contains("Content-Disposition: form-data; name=\"f%0Ai%0De%22l%0Ad1\"")); + assertTrue( + body.contains( "Content-Disposition: form-data; name=\"f%22i%0Dl%0Aef%22ie%0Ald%0D1\"; filename=\"f%0Dir%22s%0Atf%0Dil%22e%0A.txt\"")); Play.stop(app); @@ -487,6 +484,6 @@ public void multipartFormContentLength() { hello world --somerandomboundary-- */ - assertEquals(request.header(Http.HeaderNames.CONTENT_LENGTH).get(), "590"); + assertEquals("590", request.header(Http.HeaderNames.CONTENT_LENGTH).get()); } } diff --git a/core/play-java/src/test/java/play/mvc/ResultAttributesTest.java b/core/play-java/src/test/java/play/mvc/ResultAttributesTest.java index 94a8a1745dc..dee2c59c714 100644 --- a/core/play-java/src/test/java/play/mvc/ResultAttributesTest.java +++ b/core/play-java/src/test/java/play/mvc/ResultAttributesTest.java @@ -4,40 +4,34 @@ package play.mvc; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.util.Arrays; -import java.util.Collection; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Named.named; +import static org.junit.jupiter.params.provider.Arguments.arguments; + +import java.util.stream.Stream; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import play.libs.typedmap.TypedEntry; import play.libs.typedmap.TypedKey; import play.libs.typedmap.TypedMap; -@RunWith(Parameterized.class) public final class ResultAttributesTest { - @Parameters - public static Collection targets() { - return Arrays.asList(Results.ok()); + public static Stream targets() { + return Stream.of(arguments(named("OK", Results.ok()))); } - private Result result; - - public ResultAttributesTest(final Result result) { - this.result = result; - } - - @Test - public void testResult_emptyByDefault() { + @ParameterizedTest + @MethodSource("targets") + public void testResult_emptyByDefault(final Result result) { assertEquals(TypedMap.empty(), result.attrs()); } - @Test - public void testResult_addSingleAttribute() { + @ParameterizedTest + @MethodSource("targets") + public void testResult_addSingleAttribute(final Result result) { final TypedKey color = TypedKey.create("color"); final Result newResult = result.addAttr(color, "red"); @@ -46,8 +40,9 @@ public void testResult_addSingleAttribute() { assertEquals("red", newResult.attrs().get(color)); } - @Test - public void testResult_KeepCurrentAttributesWhenAddingANewOne() { + @ParameterizedTest + @MethodSource("targets") + public void testResult_KeepCurrentAttributesWhenAddingANewOne(final Result result) { final TypedKey number = TypedKey.create("number"); final TypedKey color = TypedKey.create("color"); @@ -59,8 +54,9 @@ public void testResult_KeepCurrentAttributesWhenAddingANewOne() { assertEquals("red", newResult.attrs().get(color)); } - @Test - public void testResult_OverrideExistingValue() { + @ParameterizedTest + @MethodSource("targets") + public void testResult_OverrideExistingValue(final Result result) { final TypedKey number = TypedKey.create("number"); final TypedKey color = TypedKey.create("color"); @@ -72,8 +68,9 @@ public void testResult_OverrideExistingValue() { assertEquals("white", newResult.attrs().get(color)); } - @Test - public void testResult_addMultipleAttributes() { + @ParameterizedTest + @MethodSource("targets") + public void testResult_addMultipleAttributes(final Result result) { final TypedKey number = TypedKey.create("number"); final TypedKey color = TypedKey.create("color"); @@ -86,8 +83,9 @@ public void testResult_addMultipleAttributes() { assertEquals((Long) 3L, newResult.attrs().get(number)); } - @Test - public void testResult_KeepCurrentAttributesWhenAddingMultipleOnes() { + @ParameterizedTest + @MethodSource("targets") + public void testResult_KeepCurrentAttributesWhenAddingMultipleOnes(final Result result) { final TypedKey number = TypedKey.create("number"); final TypedKey color = TypedKey.create("color"); final TypedKey direction = TypedKey.create("direction"); @@ -105,8 +103,9 @@ public void testResult_KeepCurrentAttributesWhenAddingMultipleOnes() { assertEquals("red", newResult.attrs().get(color)); } - @Test - public void testResult_OverrideExistingValueWhenAddingMultipleAttributes() { + @ParameterizedTest + @MethodSource("targets") + public void testResult_OverrideExistingValueWhenAddingMultipleAttributes(final Result result) { final TypedKey number = TypedKey.create("number"); final TypedKey color = TypedKey.create("color"); diff --git a/core/play-streams/src/test/java/play/libs/streams/AccumulatorTest.java b/core/play-streams/src/test/java/play/libs/streams/AccumulatorTest.java index 8523e0da078..c1773a7e41f 100644 --- a/core/play-streams/src/test/java/play/libs/streams/AccumulatorTest.java +++ b/core/play-streams/src/test/java/play/libs/streams/AccumulatorTest.java @@ -4,7 +4,7 @@ package play.libs.streams; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import akka.actor.ActorSystem; import akka.stream.Materializer; @@ -16,7 +16,9 @@ import java.util.concurrent.CompletionStage; import java.util.concurrent.Executor; import java.util.function.Function; -import org.junit.*; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.reactivestreams.Subscription; public class AccumulatorTest { @@ -105,14 +107,14 @@ public void through() throws Exception { 12, (int) await(sum.through(Flow.create().map(i -> i * 2)).run(source, mat))); } - @Before + @BeforeEach public void setUp() { system = ActorSystem.create(); mat = Materializer.matFromSystem(system); ec = system.dispatcher(); } - @After + @AfterEach public void tearDown() { system.terminate(); } diff --git a/core/play/src/test/java/play/core/PathsTest.java b/core/play/src/test/java/play/core/PathsTest.java index 2db905c5544..4a33fb9b116 100644 --- a/core/play/src/test/java/play/core/PathsTest.java +++ b/core/play/src/test/java/play/core/PathsTest.java @@ -4,9 +4,9 @@ package play.core; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class PathsTest { diff --git a/core/play/src/test/java/play/i18n/MessagesTest.java b/core/play/src/test/java/play/i18n/MessagesTest.java index 161f575c176..4c1baf9de36 100644 --- a/core/play/src/test/java/play/i18n/MessagesTest.java +++ b/core/play/src/test/java/play/i18n/MessagesTest.java @@ -4,10 +4,10 @@ package play.i18n; -import static org.fest.assertions.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.*; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class MessagesTest { @@ -21,7 +21,7 @@ public void testMessageCall() { String actual = messages.at("hello.world"); String expected = "hello world!"; - assertThat(actual).isEqualTo(expected); + assertEquals(expected, actual); verify(messagesApi).get(lang, "hello.world"); } diff --git a/core/play/src/test/java/play/libs/concurrent/FuturesTest.java b/core/play/src/test/java/play/libs/concurrent/FuturesTest.java index 529f1f51c84..83cd985aab1 100644 --- a/core/play/src/test/java/play/libs/concurrent/FuturesTest.java +++ b/core/play/src/test/java/play/libs/concurrent/FuturesTest.java @@ -6,28 +6,29 @@ import static java.text.MessageFormat.*; import static java.util.concurrent.CompletableFuture.completedFuture; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import akka.actor.ActorSystem; import java.time.Duration; import java.util.concurrent.CompletionStage; import java.util.concurrent.TimeUnit; -import org.junit.*; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class FuturesTest { private ActorSystem system; private Futures futures; - @Before + @BeforeEach public void setup() { system = ActorSystem.create(); futures = new DefaultFutures(new play.api.libs.concurrent.DefaultFutures(system)); } - @After + @AfterEach public void teardown() { system.terminate(); futures = null; @@ -43,7 +44,7 @@ CompletionStage callWithTimeout() { final Double actual = new MyClass().callWithTimeout().toCompletableFuture().get(1, TimeUnit.SECONDS); final Double expected = Math.PI; - assertThat(actual, equalTo(expected)); + assertEquals(expected, actual); } @Test @@ -60,7 +61,7 @@ CompletionStage callWithTimeout() { .exceptionally(e -> 100d) .get(1, TimeUnit.SECONDS); final Double expected = 100d; - assertThat(actual, equalTo(expected)); + assertEquals(expected, actual); } @Test @@ -70,8 +71,8 @@ public void successfulDelayed() throws Exception { Duration actual = Duration.ofMillis(stage.toCompletableFuture().get()); assertTrue( - format("Expected duration {0} is smaller than actual duration {1}!", expected, actual), - actual.compareTo(expected) > 0); + actual.compareTo(expected) > 0, + format("Expected duration {0} is smaller than actual duration {1}!", expected, actual)); } @Test @@ -81,8 +82,8 @@ public void failedDelayed() throws Exception { Duration actual = Duration.ofMillis(stage.toCompletableFuture().get()); assertTrue( - format("Expected duration {0} is larger from actual duration {1}!", expected, actual), - actual.compareTo(expected) < 0); + actual.compareTo(expected) < 0, + format("Expected duration {0} is larger from actual duration {1}!", expected, actual)); } @Test @@ -100,8 +101,8 @@ public void testDelay() throws Exception { Duration actual = Duration.ofMillis(stage.toCompletableFuture().get()); assertTrue( - format("Expected duration {0} is smaller than actual duration {1}!", expected, actual), - actual.compareTo(expected) > 0); + actual.compareTo(expected) > 0, + format("Expected duration {0} is smaller than actual duration {1}!", expected, actual)); } private CompletionStage computePIAsynchronously() { diff --git a/core/play/src/test/java/play/mvc/CallTest.java b/core/play/src/test/java/play/mvc/CallTest.java index 7b9fd0e0599..1857bacbf9d 100644 --- a/core/play/src/test/java/play/mvc/CallTest.java +++ b/core/play/src/test/java/play/mvc/CallTest.java @@ -4,9 +4,9 @@ package play.mvc; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.Test; +import org.junit.jupiter.api.Test; import play.mvc.Http.Request; import play.mvc.Http.RequestBuilder; diff --git a/core/play/src/test/java/play/mvc/CookieBuilderTest.java b/core/play/src/test/java/play/mvc/CookieBuilderTest.java index 8d5e82d24f6..4c9b734a0c2 100644 --- a/core/play/src/test/java/play/mvc/CookieBuilderTest.java +++ b/core/play/src/test/java/play/mvc/CookieBuilderTest.java @@ -4,9 +4,9 @@ package play.mvc; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class CookieBuilderTest { diff --git a/core/play/src/test/java/play/mvc/RangeResultsTest.java b/core/play/src/test/java/play/mvc/RangeResultsTest.java index 07337eb8f20..428b14a5c2b 100644 --- a/core/play/src/test/java/play/mvc/RangeResultsTest.java +++ b/core/play/src/test/java/play/mvc/RangeResultsTest.java @@ -4,7 +4,8 @@ package play.mvc; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrowsExactly; import static org.mockito.Mockito.*; import static play.mvc.Http.HeaderNames.*; import static play.mvc.Http.MimeTypes.*; @@ -24,7 +25,9 @@ import java.nio.file.StandardOpenOption; import java.util.Optional; import java.util.concurrent.CompletionStage; -import org.junit.*; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import scala.concurrent.Await; import scala.concurrent.duration.Duration; import scala.jdk.javaapi.FutureConverters; @@ -33,14 +36,14 @@ public class RangeResultsTest { private static Path path; - @BeforeClass + @BeforeAll public static void createFile() throws IOException { path = Paths.get("test.tmp"); Files.createFile(path); Files.write(path, "Some content for the file".getBytes(), StandardOpenOption.APPEND); } - @AfterClass + @AfterAll public static void deleteFile() throws IOException { Files.deleteIfExists(path); } @@ -368,12 +371,16 @@ public void shouldHandleNoSeekingSource() throws Exception { assertEquals("bc", getBody(result)); } - @Test(expected = IllegalArgumentException.class) + @Test public void shouldRejectBrokenSourceFunction() throws Exception { Http.Request req = mockRangeRequestWithOffset(); long entityLength = Files.size(path); byte[] data = "abcdefghijklmnopqrstuvwxyz".getBytes(); - RangeResults.ofSource(req, entityLength, brokenSeekingSourceFunction(data), "file.tmp", TEXT); + assertThrowsExactly( + IllegalArgumentException.class, + () -> + RangeResults.ofSource( + req, entityLength, brokenSeekingSourceFunction(data), "file.tmp", TEXT)); } private RangeResults.SourceFunction preSeekingSourceFunction(byte[] data) { diff --git a/core/play/src/test/java/play/mvc/ResultsTest.java b/core/play/src/test/java/play/mvc/ResultsTest.java index 53af45f54f0..0308d34853a 100644 --- a/core/play/src/test/java/play/mvc/ResultsTest.java +++ b/core/play/src/test/java/play/mvc/ResultsTest.java @@ -4,7 +4,7 @@ package play.mvc; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import akka.actor.ActorSystem; import akka.stream.Materializer; @@ -18,7 +18,10 @@ import java.util.*; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; -import org.junit.*; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import play.mvc.Http.HeaderNames; import scala.concurrent.Await; import scala.concurrent.duration.Duration; @@ -30,14 +33,14 @@ public class ResultsTest { private static final boolean INLINE_FILE = true; private static final boolean ATTACHMENT_FILE = false; - @BeforeClass + @BeforeAll public static void createFile() throws Exception { file = Paths.get("test.tmp"); Files.createFile(file); Files.write(file, "Some content for the file".getBytes(), StandardOpenOption.APPEND); } - @AfterClass + @AfterAll public static void deleteFile() throws IOException { Files.deleteIfExists(file); } @@ -85,9 +88,9 @@ public void shouldCopyCookiesWhenCallingResultAs() { // -- Path tests - @Test(expected = NullPointerException.class) + @Test() public void shouldThrowNullPointerExceptionIfPathIsNull() { - Results.ok().sendPath(null); + assertThrowsExactly(NullPointerException.class, () -> Results.ok().sendPath(null)); } @Test @@ -163,9 +166,9 @@ public void sendPathWithFileNameHasSpecialChars() { // -- File tests - @Test(expected = NullPointerException.class) + @Test public void shouldThrowNullPointerExceptionIfFileIsNull() { - Results.ok().sendFile(null); + Assertions.assertThrowsExactly(NullPointerException.class, () -> Results.ok().sendFile(null)); } @Test diff --git a/core/play/src/test/java/play/mvc/SecurityTest.java b/core/play/src/test/java/play/mvc/SecurityTest.java index 5e91a4f55d2..a5105a36836 100644 --- a/core/play/src/test/java/play/mvc/SecurityTest.java +++ b/core/play/src/test/java/play/mvc/SecurityTest.java @@ -4,7 +4,7 @@ package play.mvc; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -13,7 +13,7 @@ import java.util.concurrent.CompletionStage; import java.util.concurrent.TimeUnit; import java.util.function.Function; -import org.junit.Test; +import org.junit.jupiter.api.Test; import play.inject.Injector; public class SecurityTest { diff --git a/documentation/manual/working/javaGuide/main/tests/JavaTest.md b/documentation/manual/working/javaGuide/main/tests/JavaTest.md index 79e4fd89c3a..5b5aceb7944 100644 --- a/documentation/manual/working/javaGuide/main/tests/JavaTest.md +++ b/documentation/manual/working/javaGuide/main/tests/JavaTest.md @@ -2,7 +2,7 @@ # Testing your application -Writing tests for your application can be an involved process. Play supports [JUnit](https://junit.org/junit4/) and provides helpers and application stubs to make testing your application as easy as possible. +Writing tests for your application can be an involved process. Play supports [JUnit](https://junit.org/junit5/) and provides helpers and application stubs to make testing your application as easy as possible. ## Overview @@ -20,7 +20,7 @@ Testing in Play is based on [sbt](https://www.scala-sbt.org/), and a full descri ## Using JUnit -The default way to test a Play application is with [JUnit](https://junit.org/junit4/). +The default way to test a Play application is with [JUnit](https://junit.org/junit5/). @[test-simple](code/javaguide/tests/SimpleTest.java) diff --git a/persistence/play-java-jdbc/src/test/java/play/db/DatabaseTest.java b/persistence/play-java-jdbc/src/test/java/play/db/DatabaseTest.java index 3eb664d6910..87284868177 100644 --- a/persistence/play-java-jdbc/src/test/java/play/db/DatabaseTest.java +++ b/persistence/play-java-jdbc/src/test/java/play/db/DatabaseTest.java @@ -4,9 +4,7 @@ package play.db; -import static org.hamcrest.CoreMatchers.*; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertThrows; +import static org.junit.jupiter.api.Assertions.*; import com.google.common.collect.ImmutableMap; import java.sql.Connection; @@ -14,7 +12,7 @@ import java.sql.SQLException; import java.util.Map; import org.jdbcdslog.ConnectionPoolDataSourceProxy; -import org.junit.Test; +import org.junit.jupiter.api.Test; import play.api.libs.JNDI; public class DatabaseTest { @@ -22,16 +20,16 @@ public class DatabaseTest { @Test public void createDatabase() { Database db = Databases.createFrom("test", "org.h2.Driver", "jdbc:h2:mem:test"); - assertThat(db.getName(), equalTo("test")); - assertThat(db.getUrl(), equalTo("jdbc:h2:mem:test")); + assertEquals("test", db.getName()); + assertEquals("jdbc:h2:mem:test", db.getUrl()); db.shutdown(); } @Test public void createDefaultDatabase() { Database db = Databases.createFrom("org.h2.Driver", "jdbc:h2:mem:default"); - assertThat(db.getName(), equalTo("default")); - assertThat(db.getUrl(), equalTo("jdbc:h2:mem:default")); + assertEquals("default", db.getName()); + assertEquals("jdbc:h2:mem:default", db.getUrl()); db.shutdown(); } @@ -39,29 +37,29 @@ public void createDefaultDatabase() { public void createConfiguredDatabase() throws Exception { Map config = ImmutableMap.of("jndiName", "DefaultDS"); Database db = Databases.createFrom("test", "org.h2.Driver", "jdbc:h2:mem:test", config); - assertThat(db.getName(), equalTo("test")); - assertThat(db.getUrl(), equalTo("jdbc:h2:mem:test")); + assertEquals("test", db.getName()); + assertEquals("jdbc:h2:mem:test", db.getUrl()); // Forces the data source initialization, and then JNDI registration. db.getDataSource(); - assertThat(JNDI.initialContext().lookup("DefaultDS"), equalTo(db.getDataSource())); + assertEquals(db.getDataSource(), JNDI.initialContext().lookup("DefaultDS")); db.shutdown(); } @Test public void createDefaultInMemoryDatabase() { Database db = Databases.inMemory(); - assertThat(db.getName(), equalTo("default")); - assertThat(db.getUrl(), equalTo("jdbc:h2:mem:default")); + assertEquals("default", db.getName()); + assertEquals("jdbc:h2:mem:default", db.getUrl()); db.shutdown(); } @Test public void createNamedInMemoryDatabase() { Database db = Databases.inMemory("test"); - assertThat(db.getName(), equalTo("test")); - assertThat(db.getUrl(), equalTo("jdbc:h2:mem:test")); + assertEquals("test", db.getName()); + assertEquals("jdbc:h2:mem:test", db.getUrl()); db.shutdown(); } @@ -71,8 +69,8 @@ public void createInMemoryDatabaseWithUrlOptions() { Map config = ImmutableMap.of(); Database db = Databases.inMemory("test", options, config); - assertThat(db.getName(), equalTo("test")); - assertThat(db.getUrl(), equalTo("jdbc:h2:mem:test;MODE=MySQL")); + assertEquals("test", db.getName()); + assertEquals("jdbc:h2:mem:test;MODE=MySQL", db.getUrl()); db.shutdown(); } @@ -80,13 +78,13 @@ public void createInMemoryDatabaseWithUrlOptions() { @Test public void createConfiguredInMemoryDatabase() throws Exception { Database db = Databases.inMemoryWith("jndiName", "DefaultDS"); - assertThat(db.getName(), equalTo("default")); - assertThat(db.getUrl(), equalTo("jdbc:h2:mem:default")); + assertEquals("default", db.getName()); + assertEquals("jdbc:h2:mem:default", db.getUrl()); // Forces the data source initialization, and then JNDI registration. db.getDataSource(); - assertThat(JNDI.initialContext().lookup("DefaultDS"), equalTo(db.getDataSource())); + assertEquals(db.getDataSource(), JNDI.initialContext().lookup("DefaultDS")); db.shutdown(); } @@ -112,8 +110,8 @@ public void enableAutocommitByDefault() throws Exception { c1.createStatement().execute("create table test (id bigint not null, name varchar(255))"); c1.createStatement().execute("insert into test (id, name) values (1, 'alice')"); ResultSet results = c2.createStatement().executeQuery("select * from test"); - assertThat(results.next(), is(true)); - assertThat(results.next(), is(false)); + assertTrue(results.next()); + assertFalse(results.next()); } db.shutdown(); @@ -133,12 +131,12 @@ public void provideConnectionHelpers() { db.withConnection( c -> { ResultSet results = c.createStatement().executeQuery("select * from test"); - assertThat(results.next(), is(true)); - assertThat(results.next(), is(false)); + assertTrue(results.next()); + assertFalse(results.next()); return true; }); - assertThat(result, is(true)); + assertTrue(result); db.shutdown(); } @@ -158,11 +156,11 @@ public void provideConnectionHelpersWithAutoCommitIsFalse() { db.withConnection( c -> { ResultSet results = c.createStatement().executeQuery("select * from test"); - assertThat(results.next(), is(false)); + assertFalse(results.next()); return true; }); - assertThat(result, is(true)); + assertTrue(result); db.shutdown(); } @@ -180,13 +178,13 @@ public void provideTransactionHelper() { return true; }); - assertThat(created, is(true)); + assertTrue(created); db.withConnection( c -> { ResultSet results = c.createStatement().executeQuery("select * from test"); - assertThat(results.next(), is(true)); - assertThat(results.next(), is(false)); + assertTrue(results.next()); + assertFalse(results.next()); }); try { @@ -196,14 +194,14 @@ public void provideTransactionHelper() { throw new RuntimeException("boom"); }); } catch (Exception e) { - assertThat(e.getMessage(), equalTo("boom")); + assertEquals("boom", e.getMessage()); } db.withConnection( c -> { ResultSet results = c.createStatement().executeQuery("select * from test"); - assertThat(results.next(), is(true)); - assertThat(results.next(), is(false)); + assertTrue(results.next()); + assertFalse(results.next()); }); db.shutdown(); @@ -215,16 +213,16 @@ public void notSupplyConnectionsAfterShutdown() throws Exception { db.getConnection().close(); db.shutdown(); SQLException sqlException = assertThrows(SQLException.class, () -> db.getConnection().close()); - assertThat(sqlException.getMessage(), endsWith("has been closed.")); + assertTrue(sqlException.getMessage().endsWith("has been closed.")); } @Test public void useConnectionPoolDataSourceProxyWhenLogSqlIsTrue() throws Exception { Map config = ImmutableMap.of("jndiName", "DefaultDS", "logSql", "true"); Database db = Databases.createFrom("test", "org.h2.Driver", "jdbc:h2:mem:test", config); - assertThat(db.getDataSource(), instanceOf(ConnectionPoolDataSourceProxy.class)); - assertThat( - JNDI.initialContext().lookup("DefaultDS"), instanceOf(ConnectionPoolDataSourceProxy.class)); + assertInstanceOf(ConnectionPoolDataSourceProxy.class, db.getDataSource()); + assertInstanceOf( + ConnectionPoolDataSourceProxy.class, JNDI.initialContext().lookup("DefaultDS")); db.shutdown(); } @@ -242,13 +240,13 @@ public void manualSetupTransactionIsolationLevel() throws Exception { return true; }); - assertThat(created, is(true)); + assertTrue(created); db.withConnection( c -> { ResultSet results = c.createStatement().executeQuery("select * from test"); - assertThat(results.next(), is(true)); - assertThat(results.next(), is(false)); + assertTrue(results.next()); + assertFalse(results.next()); }); db.shutdown(); diff --git a/persistence/play-java-jdbc/src/test/java/play/db/NamedDatabaseTest.java b/persistence/play-java-jdbc/src/test/java/play/db/NamedDatabaseTest.java index a1f10b1adbe..ac3981cf25c 100644 --- a/persistence/play-java-jdbc/src/test/java/play/db/NamedDatabaseTest.java +++ b/persistence/play-java-jdbc/src/test/java/play/db/NamedDatabaseTest.java @@ -4,17 +4,15 @@ package play.db; -import static org.hamcrest.CoreMatchers.*; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrowsExactly; import com.google.common.collect.ImmutableMap; import com.google.inject.Guice; import com.google.inject.Injector; import java.util.Map; import javax.inject.Inject; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; import play.ApplicationLoader.Context; import play.Environment; import play.inject.guice.GuiceApplicationBuilder; @@ -22,87 +20,86 @@ public class NamedDatabaseTest { - @Rule public ExpectedException exception = ExpectedException.none(); - @Test public void bindDatabasesByName() { Map config = ImmutableMap.of( - "db.default.driver", "org.h2.Driver", - "db.default.url", "jdbc:h2:mem:default", - "db.other.driver", "org.h2.Driver", - "db.other.url", "jdbc:h2:mem:other"); + "db.default.driver", + "org.h2.Driver", + "db.default.url", + "jdbc:h2:mem:default", + "db.other.driver", + "org.h2.Driver", + "db.other.url", + "jdbc:h2:mem:other"); Injector injector = createInjector(config); - assertThat( - injector.getInstance(DefaultComponent.class).db.getUrl(), equalTo("jdbc:h2:mem:default")); - assertThat( - injector.getInstance(NamedDefaultComponent.class).db.getUrl(), - equalTo("jdbc:h2:mem:default")); - assertThat( - injector.getInstance(NamedOtherComponent.class).db.getUrl(), equalTo("jdbc:h2:mem:other")); + assertEquals("jdbc:h2:mem:default", injector.getInstance(DefaultComponent.class).db.getUrl()); + assertEquals( + "jdbc:h2:mem:default", injector.getInstance(NamedDefaultComponent.class).db.getUrl()); + assertEquals("jdbc:h2:mem:other", injector.getInstance(NamedOtherComponent.class).db.getUrl()); + } + + private Injector createInjector(Map config) { + GuiceApplicationBuilder builder = + new GuiceApplicationLoader().builder(new Context(Environment.simple(), config)); + return Guice.createInjector(builder.applicationModule()); } @Test public void notBindDefaultDatabaseWithoutConfiguration() { Map config = - ImmutableMap.of( - "db.other.driver", "org.h2.Driver", - "db.other.url", "jdbc:h2:mem:other"); + ImmutableMap.of("db.other.driver", "org.h2.Driver", "db.other.url", "jdbc:h2:mem:other"); Injector injector = createInjector(config); - assertThat( - injector.getInstance(NamedOtherComponent.class).db.getUrl(), equalTo("jdbc:h2:mem:other")); - exception.expect(com.google.inject.ConfigurationException.class); - injector.getInstance(DefaultComponent.class); + assertEquals("jdbc:h2:mem:other", injector.getInstance(NamedOtherComponent.class).db.getUrl()); + assertThrowsExactly( + com.google.inject.ConfigurationException.class, + () -> injector.getInstance(DefaultComponent.class)); } @Test public void notBindNamedDefaultDatabaseWithoutConfiguration() { Map config = - ImmutableMap.of( - "db.other.driver", "org.h2.Driver", - "db.other.url", "jdbc:h2:mem:other"); + ImmutableMap.of("db.other.driver", "org.h2.Driver", "db.other.url", "jdbc:h2:mem:other"); Injector injector = createInjector(config); - assertThat( - injector.getInstance(NamedOtherComponent.class).db.getUrl(), equalTo("jdbc:h2:mem:other")); - exception.expect(com.google.inject.ConfigurationException.class); - injector.getInstance(NamedDefaultComponent.class); + assertEquals("jdbc:h2:mem:other", injector.getInstance(NamedOtherComponent.class).db.getUrl()); + assertThrowsExactly( + com.google.inject.ConfigurationException.class, + () -> injector.getInstance(NamedDefaultComponent.class)); } @Test public void allowDefaultDatabaseNameToBeConfigured() { Map config = ImmutableMap.of( - "play.db.default", "other", - "db.other.driver", "org.h2.Driver", - "db.other.url", "jdbc:h2:mem:other"); + "play.db.default", + "other", + "db.other.driver", + "org.h2.Driver", + "db.other.url", + "jdbc:h2:mem:other"); Injector injector = createInjector(config); - assertThat( - injector.getInstance(DefaultComponent.class).db.getUrl(), equalTo("jdbc:h2:mem:other")); - assertThat( - injector.getInstance(NamedOtherComponent.class).db.getUrl(), equalTo("jdbc:h2:mem:other")); - exception.expect(com.google.inject.ConfigurationException.class); - injector.getInstance(NamedDefaultComponent.class); + assertEquals("jdbc:h2:mem:other", injector.getInstance(DefaultComponent.class).db.getUrl()); + assertEquals("jdbc:h2:mem:other", injector.getInstance(NamedOtherComponent.class).db.getUrl()); + + assertThrowsExactly( + com.google.inject.ConfigurationException.class, + () -> injector.getInstance(NamedDefaultComponent.class)); } @Test public void allowDbConfigKeyToBeConfigured() { Map config = ImmutableMap.of( - "play.db.config", "databases", - "databases.default.driver", "org.h2.Driver", - "databases.default.url", "jdbc:h2:mem:default"); + "play.db.config", + "databases", + "databases.default.driver", + "org.h2.Driver", + "databases.default.url", + "jdbc:h2:mem:default"); Injector injector = createInjector(config); - assertThat( - injector.getInstance(DefaultComponent.class).db.getUrl(), equalTo("jdbc:h2:mem:default")); - assertThat( - injector.getInstance(NamedDefaultComponent.class).db.getUrl(), - equalTo("jdbc:h2:mem:default")); - } - - private Injector createInjector(Map config) { - GuiceApplicationBuilder builder = - new GuiceApplicationLoader().builder(new Context(Environment.simple(), config)); - return Guice.createInjector(builder.applicationModule()); + assertEquals("jdbc:h2:mem:default", injector.getInstance(DefaultComponent.class).db.getUrl()); + assertEquals( + "jdbc:h2:mem:default", injector.getInstance(NamedDefaultComponent.class).db.getUrl()); } public static class DefaultComponent { diff --git a/persistence/play-java-jpa/src/test/java/play/db/jpa/JPAApiTest.java b/persistence/play-java-jpa/src/test/java/play/db/jpa/JPAApiTest.java index 079bbe8939f..c9e89ef88d0 100644 --- a/persistence/play-java-jpa/src/test/java/play/db/jpa/JPAApiTest.java +++ b/persistence/play-java-jpa/src/test/java/play/db/jpa/JPAApiTest.java @@ -4,27 +4,28 @@ package play.db.jpa; -import static org.hamcrest.CoreMatchers.*; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.*; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import jakarta.persistence.EntityManager; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashSet; -import java.util.Set; +import java.util.*; import java.util.stream.Collectors; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExternalResource; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.*; import play.db.Database; import play.db.Databases; import play.db.jpa.DefaultJPAConfig.JPAConfigProvider; public class JPAApiTest { + @RegisterExtension TestDatabaseExtension db = new TestDatabaseExtension(); - @Rule public TestDatabase db = new TestDatabase(); + @Test + public void shouldWorkWithEmptyConfiguration() { + String configString = ""; + Set unitNames = getConfiguredPersistenceUnitNames(configString); + assertTrue(unitNames.isEmpty()); + } private Set getConfiguredPersistenceUnitNames(String configString) { Config overrides = ConfigFactory.parseString(configString); @@ -33,33 +34,25 @@ private Set getConfiguredPersistenceUnitNames(String configString) { .get().persistenceUnits().stream().map(unit -> unit.unitName).collect(Collectors.toSet()); } - @Test - public void shouldWorkWithEmptyConfiguration() { - String configString = ""; - Set unitNames = getConfiguredPersistenceUnitNames(configString); - assertThat(unitNames, equalTo(Collections.emptySet())); - } - @Test public void shouldWorkWithSingleValue() { String configString = "jpa.default = defaultPersistenceUnit"; Set unitNames = getConfiguredPersistenceUnitNames(configString); - assertThat(unitNames, equalTo(new HashSet<>(Arrays.asList("defaultPersistenceUnit")))); + assertEquals(unitNames, new HashSet<>(List.of("defaultPersistenceUnit"))); } @Test public void shouldWorkWithMultipleValues() { String configString = "jpa.default = defaultPersistenceUnit\n" + "jpa.number2 = number2Unit"; Set unitNames = getConfiguredPersistenceUnitNames(configString); - assertThat( - unitNames, equalTo(new HashSet<>(Arrays.asList("defaultPersistenceUnit", "number2Unit")))); + assertEquals(unitNames, new HashSet<>(Arrays.asList("defaultPersistenceUnit", "number2Unit"))); } @Test public void shouldWorkWithEmptyConfigurationAtConfiguredLocation() { String configString = "play.jpa.config = myconfig.jpa"; Set unitNames = getConfiguredPersistenceUnitNames(configString); - assertThat(unitNames, equalTo(Collections.emptySet())); + assertTrue(unitNames.isEmpty()); } @Test @@ -67,7 +60,7 @@ public void shouldWorkWithSingleValueAtConfiguredLocation() { String configString = "play.jpa.config = myconfig.jpa\n" + "myconfig.jpa.default = defaultPersistenceUnit"; Set unitNames = getConfiguredPersistenceUnitNames(configString); - assertThat(unitNames, equalTo(new HashSet<>(Arrays.asList("defaultPersistenceUnit")))); + assertEquals(new HashSet<>(List.of("defaultPersistenceUnit")), unitNames); } @Test @@ -77,14 +70,13 @@ public void shouldWorkWithMultipleValuesAtConfiguredLocation() { + "myconfig.jpa.default = defaultPersistenceUnit\n" + "myconfig.jpa.number2 = number2Unit"; Set unitNames = getConfiguredPersistenceUnitNames(configString); - assertThat( - unitNames, equalTo(new HashSet<>(Arrays.asList("defaultPersistenceUnit", "number2Unit")))); + assertEquals(unitNames, new HashSet<>(Arrays.asList("defaultPersistenceUnit", "number2Unit"))); } @Test public void shouldBeAbleToGetAnEntityManagerWithAGivenName() { EntityManager em = db.jpa.em("default"); - assertThat(em, notNullValue()); + assertNotNull(em); } @Test @@ -99,10 +91,21 @@ public void shouldExecuteAFunctionBlockUsingAEntityManager() { db.jpa.withTransaction( entityManager -> { TestEntity entity = TestEntity.find(1L, entityManager); - assertThat(entity.name, equalTo("alice")); + assertEquals("alice", entity.name); }); } + private TestEntity createTestEntity() { + return createTestEntity(1L); + } + + private TestEntity createTestEntity(Long id) { + TestEntity entity = new TestEntity(); + entity.id = id; + entity.name = "alice"; + return entity; + } + @Test public void shouldExecuteAFunctionBlockUsingASpecificNamedEntityManager() { db.jpa.withTransaction( @@ -116,7 +119,7 @@ public void shouldExecuteAFunctionBlockUsingASpecificNamedEntityManager() { db.jpa.withTransaction( entityManager -> { TestEntity entity = TestEntity.find(1L, entityManager); - assertThat(entity.name, equalTo("alice")); + assertEquals("alice", entity.name); }); } @@ -134,21 +137,10 @@ public void shouldExecuteAFunctionBlockAsAReadOnlyTransaction() { db.jpa.withTransaction( entityManager -> { TestEntity entity = TestEntity.find(1L, entityManager); - assertThat(entity, nullValue()); + assertNull(entity); }); } - private TestEntity createTestEntity() { - return createTestEntity(1L); - } - - private TestEntity createTestEntity(Long id) { - TestEntity entity = new TestEntity(); - entity.id = id; - entity.name = "alice"; - return entity; - } - @Test public void shouldExecuteASupplierBlockInsideATransaction() throws Exception { db.jpa.withTransaction( @@ -160,7 +152,7 @@ public void shouldExecuteASupplierBlockInsideATransaction() throws Exception { db.jpa.withTransaction( entityManager -> { TestEntity entity = TestEntity.find(1L, entityManager); - assertThat(entity.name, equalTo("alice")); + assertEquals("alice", entity.name); }); } @@ -176,12 +168,12 @@ public void shouldNestTransactions() { db.jpa.withTransaction( entityManagerInner -> { TestEntity entity2 = TestEntity.find(2L, entityManagerInner); - assertThat(entity2, nullValue()); + assertNull(entity2); }); // Verify that we can still access the EntityManager TestEntity entity3 = TestEntity.find(2L, entityManager); - assertThat(entity3, equalTo(entity)); + assertEquals(entity, entity3); }); } @@ -204,16 +196,16 @@ public void shouldRollbackInnerTransactionOnly() { // Verify that we can still access the EntityManager TestEntity entity3 = TestEntity.find(2L, entityManager); - assertThat(entity3, equalTo(entity)); + assertEquals(entity, entity3); }); db.jpa.withTransaction( entityManager -> { TestEntity entity = TestEntity.find(3L, entityManager); - assertThat(entity, nullValue()); + assertNull(entity); TestEntity entity2 = TestEntity.find(2L, entityManager); - assertThat(entity2.name, equalTo("alice")); + assertEquals("alice", entity2.name); }); } @@ -234,7 +226,7 @@ public void shouldRollbackOuterTransactionOnly() { // Verify that we can still access the EntityManager TestEntity entity3 = TestEntity.find(2L, entityManager); - assertThat(entity3, equalTo(entity)); + assertEquals(entity, entity3); entityManager.getTransaction().setRollbackOnly(); }); @@ -242,14 +234,14 @@ public void shouldRollbackOuterTransactionOnly() { db.jpa.withTransaction( entityManager -> { TestEntity entity = TestEntity.find(3L, entityManager); - assertThat(entity.name, equalTo("alice")); + assertEquals("alice", entity.name); TestEntity entity2 = TestEntity.find(2L, entityManager); - assertThat(entity2, nullValue()); + assertNull(entity2); }); } - public static class TestDatabase extends ExternalResource { + public static class TestDatabaseExtension implements BeforeEachCallback, AfterEachCallback { Database database; JPAApi jpa; @@ -261,16 +253,16 @@ public void execute(final String sql) { } @Override - public void before() { - database = Databases.inMemoryWith("jndiName", "DefaultDS"); - execute("create table TestEntity (id bigint not null, name varchar(255));"); - jpa = new DefaultJPAApi(DefaultJPAConfig.of("default", "defaultPersistenceUnit")).start(); + public void afterEach(ExtensionContext context) throws Exception { + jpa.shutdown(); + database.shutdown(); } @Override - public void after() { - jpa.shutdown(); - database.shutdown(); + public void beforeEach(ExtensionContext context) throws Exception { + database = Databases.inMemoryWith("jndiName", "DefaultDS"); + execute("create table TestEntity (id bigint not null, name varchar(255));"); + jpa = new DefaultJPAApi(DefaultJPAConfig.of("default", "defaultPersistenceUnit")).start(); } } } diff --git a/persistence/play-jdbc-evolutions/src/test/java/play/db/evolutions/EvolutionsTest.java b/persistence/play-jdbc-evolutions/src/test/java/play/db/evolutions/EvolutionsTest.java index 98488203021..43380461ba2 100644 --- a/persistence/play-jdbc-evolutions/src/test/java/play/db/evolutions/EvolutionsTest.java +++ b/persistence/play-jdbc-evolutions/src/test/java/play/db/evolutions/EvolutionsTest.java @@ -4,12 +4,14 @@ package play.db.evolutions; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; -import org.junit.*; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import play.db.Database; import play.db.Databases; @@ -27,26 +29,24 @@ public void testEvolutions() throws Exception { assertTrue(resultSet.next()); Evolutions.cleanupEvolutions(database); - try { - // Ensure tables don't exist - executeStatement("select * from test"); - fail("SQL statement should have thrown an exception"); - } catch (SQLException se) { - // pass - } + + assertThrows( + SQLException.class, + () -> executeStatement("select * from test"), + "SQL statement should have thrown an exception"); } private ResultSet executeStatement(String statement) throws Exception { return connection.prepareStatement(statement).executeQuery(); } - @Before + @BeforeEach public void createDatabase() { database = Databases.inMemory(); connection = database.getConnection(); } - @After + @AfterEach public void shutdown() { database.shutdown(); database = null; diff --git a/project/BuildSettings.scala b/project/BuildSettings.scala index 48f45c5e7e7..8836d09df3c 100644 --- a/project/BuildSettings.scala +++ b/project/BuildSettings.scala @@ -26,6 +26,7 @@ import interplay._ import interplay.Omnidoc.autoImport._ import interplay.PlayBuildBase.autoImport._ import interplay.ScalaVersions._ +import net.aichler.jupiter.sbt.Import.jupiterTestFramework import xerial.sbt.Sonatype.autoImport.sonatypeProfileName object BuildSettings { @@ -118,7 +119,7 @@ object BuildSettings { (Test / javaOptions) ++= Seq("-XX:MaxMetaspaceSize=384m", "-Xmx512m", "-Xms128m"), testOptions ++= Seq( Tests.Argument(TestFrameworks.Specs2, "showtimes"), - Tests.Argument(TestFrameworks.JUnit, "-v") + Tests.Argument(jupiterTestFramework, "-v") ), version ~= { v => v + diff --git a/project/Dependencies.scala b/project/Dependencies.scala index 81c2007d259..09fb402c8e5 100644 --- a/project/Dependencies.scala +++ b/project/Dependencies.scala @@ -150,13 +150,17 @@ object Dependencies { .exclude("org.springframework", "spring-core") ) ++ specs2Deps.map(_ % Test) - val junitInterface = "com.github.sbt" % "junit-interface" % "0.13.3" - val junit = "junit" % "junit" % "4.13.2" + val junit4 = "junit" % "junit" % "4.13.2" + val junit4Interface = "com.github.sbt" % "junit-interface" % "0.13.3" + + val junit5 = "org.junit.jupiter" % "junit-jupiter" % "5.9.3" + val junit5Interface = "net.aichler" % "jupiter-interface" % "0.11.1" val javaTestDeps = Seq( - junit, - junitInterface, - "org.easytesting" % "fest-assert" % "1.4", + junit4, + junit4Interface, + junit5, + junit5Interface, mockitoAll, logback ).map(_ % Test) @@ -277,7 +281,7 @@ object Dependencies { // See https://repo1.maven.org/maven2/io/fluentlenium/fluentlenium-parent/6.0.0/fluentlenium-parent-6.0.0.pom val seleniumVersion = "4.9.1" - val testDependencies = Seq(junit, junitInterface, guava, logback) ++ Seq( + val testDependencies = Seq(junit4, junit4Interface, junit5, junit5Interface, guava, logback) ++ Seq( ("io.fluentlenium" % "fluentlenium-core" % fluentleniumVersion).exclude("org.jboss.netty", "netty"), // htmlunit-driver uses an open range to selenium dependencies. This is slightly // slowing down the build. So the open range deps were removed and we can re-add diff --git a/project/plugins.sbt b/project/plugins.sbt index 54150b5bf25..2cb3c5ddb5e 100644 --- a/project/plugins.sbt +++ b/project/plugins.sbt @@ -32,6 +32,7 @@ addSbtPlugin("pl.project13.scala" % "sbt-jmh" % sbtJmh) addSbtPlugin("de.heikoseeberger" % "sbt-header" % sbtHeader) addSbtPlugin("org.scalameta" % "sbt-scalafmt" % scalafmt) addSbtPlugin("com.github.sbt" % "sbt-ci-release" % "1.5.12") +addSbtPlugin("net.aichler" % "sbt-jupiter-interface" % "0.11.1") addSbtPlugin("com.lightbend.akka" % "sbt-akka-version-check" % "0.1") diff --git a/testkit/play-test/src/test/java/play/test/HelpersTest.java b/testkit/play-test/src/test/java/play/test/HelpersTest.java index 7d77c1d738d..7e2b4b79bd8 100644 --- a/testkit/play-test/src/test/java/play/test/HelpersTest.java +++ b/testkit/play-test/src/test/java/play/test/HelpersTest.java @@ -4,8 +4,7 @@ package play.test; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.*; import static play.test.Helpers.POST; import akka.actor.ActorSystem; @@ -15,8 +14,7 @@ import java.util.Collections; import java.util.HashMap; import java.util.Map; -import org.hamcrest.CoreMatchers; -import org.junit.Test; +import org.junit.jupiter.api.Test; import play.Application; import play.mvc.Http; import play.mvc.Result; @@ -32,35 +30,35 @@ public class HelpersTest { @Test public void shouldCreateASimpleFakeRequest() { Http.RequestImpl request = Helpers.fakeRequest().build(); - assertThat(request.method(), equalTo("GET")); - assertThat(request.path(), equalTo("/")); + assertEquals("GET", request.method()); + assertEquals("/", request.path()); } @Test public void shouldCreateAFakeRequestWithMethodAndUri() { Http.RequestImpl request = Helpers.fakeRequest("POST", "/my-uri").build(); - assertThat(request.method(), equalTo("POST")); - assertThat(request.path(), equalTo("/my-uri")); + assertEquals("POST", request.method()); + assertEquals("/my-uri", request.path()); } @Test public void shouldAddHostHeaderToFakeRequests() { Http.RequestImpl request = Helpers.fakeRequest().build(); - assertThat(request.host(), equalTo("localhost")); + assertEquals("localhost", request.host()); } @Test public void shouldCreateFakeApplicationsWithAnInMemoryDatabase() { Application application = Helpers.fakeApplication(Helpers.inMemoryDatabase()); - assertThat(application.config().getString("db.default.driver"), CoreMatchers.notNullValue()); - assertThat(application.config().getString("db.default.url"), CoreMatchers.notNullValue()); + assertNotNull(application.config().getString("db.default.driver")); + assertNotNull(application.config().getString("db.default.url")); } @Test public void shouldCreateFakeApplicationsWithAnNamedInMemoryDatabase() { Application application = Helpers.fakeApplication(Helpers.inMemoryDatabase("testDb")); - assertThat(application.config().getString("db.testDb.driver"), CoreMatchers.notNullValue()); - assertThat(application.config().getString("db.testDb.url"), CoreMatchers.notNullValue()); + assertNotNull(application.config().getString("db.testDb.driver")); + assertNotNull(application.config().getString("db.testDb.url")); } @Test @@ -70,18 +68,17 @@ public void shouldCreateFakeApplicationsWithAnNamedInMemoryDatabaseAndConnection options.put("ttl", "10"); Application application = Helpers.fakeApplication(Helpers.inMemoryDatabase("testDb", options)); - assertThat(application.config().getString("db.testDb.driver"), CoreMatchers.notNullValue()); - assertThat(application.config().getString("db.testDb.url"), CoreMatchers.notNullValue()); - assertThat( - application.config().getString("db.testDb.url"), CoreMatchers.containsString("username")); - assertThat(application.config().getString("db.testDb.url"), CoreMatchers.containsString("ttl")); + assertNotNull(application.config().getString("db.testDb.driver")); + assertNotNull(application.config().getString("db.testDb.url")); + assertTrue(application.config().getString("db.testDb.url").contains("username")); + assertTrue(application.config().getString("db.testDb.url").contains("ttl")); } @Test public void shouldExtractContentAsBytesFromAResult() { Result result = Results.ok("Test content"); ByteString contentAsBytes = Helpers.contentAsBytes(result); - assertThat(contentAsBytes, equalTo(ByteString.fromString("Test content"))); + assertEquals(ByteString.fromString("Test content"), contentAsBytes); } @Test @@ -93,7 +90,7 @@ public void shouldExtractContentAsBytesFromAResultUsingAMaterializer() throws Ex Result result = Results.ok("Test content"); ByteString contentAsBytes = Helpers.contentAsBytes(result, mat); - assertThat(contentAsBytes, equalTo(ByteString.fromString("Test content"))); + assertEquals(ByteString.fromString("Test content"), contentAsBytes); } finally { Future future = actorSystem.terminate(); Await.result(future, Duration.create("5s")); @@ -104,21 +101,21 @@ public void shouldExtractContentAsBytesFromAResultUsingAMaterializer() throws Ex public void shouldExtractContentAsBytesFromTwirlContent() { Content content = Html.apply("Test content"); ByteString contentAsBytes = Helpers.contentAsBytes(content); - assertThat(contentAsBytes, equalTo(ByteString.fromString("Test content"))); + assertEquals(ByteString.fromString("Test content"), contentAsBytes); } @Test public void shouldExtractContentAsStringFromTwirlContent() { Content content = Html.apply("Test content"); String contentAsString = Helpers.contentAsString(content); - assertThat(contentAsString, equalTo("Test content")); + assertEquals("Test content", contentAsString); } @Test public void shouldExtractContentAsStringFromAResult() { Result result = Results.ok("Test content"); String contentAsString = Helpers.contentAsString(result); - assertThat(contentAsString, equalTo("Test content")); + assertEquals("Test content", contentAsString); } @Test @@ -130,7 +127,7 @@ public void shouldExtractContentAsStringFromAResultUsingAMaterializer() throws E Result result = Results.ok("Test content"); String contentAsString = Helpers.contentAsString(result, mat); - assertThat(contentAsString, equalTo("Test content")); + assertEquals("Test content", contentAsString); } finally { Future future = actorSystem.terminate(); Await.result(future, Duration.create("5s")); @@ -143,7 +140,7 @@ public void shouldSuccessfullyExecutePostRequestWithEmptyBody() { Application app = Helpers.fakeApplication(); Result result = Helpers.route(app, request); - assertThat(result.status(), equalTo(404)); + assertEquals(404, result.status()); } @Test @@ -154,14 +151,14 @@ public void shouldSuccessfullyExecutePostRequestWithMultipartFormData() { Http.RequestBuilder request = new Http.RequestBuilder().method(POST).bodyMultipart(postParams, Collections.emptyList()); Result result = Helpers.route(app, request); - assertThat(result.status(), equalTo(404)); + assertEquals(404, result.status()); } @Test public void shouldReturnProperHasBodyValueForFakeRequest() { // Does not set a Content-Length and also not a Transfer-Encoding header, sets null as body Http.Request request = Helpers.fakeRequest("POST", "/uri").build(); - assertThat(request.hasBody(), equalTo(false)); + assertFalse(request.hasBody()); } @Test @@ -169,7 +166,7 @@ public void shouldReturnProperHasBodyValueForEmptyRawBuffer() { // Does set a Content-Length header Http.Request request = Helpers.fakeRequest("POST", "/uri").bodyRaw(ByteString.emptyByteString()).build(); - assertThat(request.hasBody(), equalTo(false)); + assertFalse(request.hasBody()); } @Test @@ -177,6 +174,6 @@ public void shouldReturnProperHasBodyValueForNonEmptyRawBuffer() { // Does set a Content-Length header Http.Request request = Helpers.fakeRequest("POST", "/uri").bodyRaw(ByteString.fromString("a")).build(); - assertThat(request.hasBody(), equalTo(true)); + assertTrue(request.hasBody()); } } diff --git a/testkit/play-test/src/test/java/play/test/TestServerTest.java b/testkit/play-test/src/test/java/play/test/TestServerTest.java index df189ee5362..65177466c78 100644 --- a/testkit/play-test/src/test/java/play/test/TestServerTest.java +++ b/testkit/play-test/src/test/java/play/test/TestServerTest.java @@ -4,10 +4,10 @@ package play.test; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TestServerTest { @Test @@ -15,13 +15,13 @@ public void shouldReturnHttpPort() { int testServerPort = play.api.test.Helpers.testServerPort(); final TestServer testServer = Helpers.testServer(testServerPort); testServer.start(); - assertTrue("No value for http port", testServer.getRunningHttpPort().isPresent()); + assertTrue(testServer.getRunningHttpPort().isPresent(), "No value for http port"); assertFalse( - "https port value is present, but was not set", - testServer.getRunningHttpsPort().isPresent()); + testServer.getRunningHttpsPort().isPresent(), + "https port value is present, but was not set"); assertTrue( - "The os provided http port is not greater than 0", - testServer.getRunningHttpPort().getAsInt() > 0); + testServer.getRunningHttpPort().getAsInt() > 0, + "The os provided http port is not greater than 0"); testServer.stop(); } @@ -31,14 +31,14 @@ public void shouldReturnHttpAndHttpsPorts() { int httpsPort = 0; final TestServer testServer = Helpers.testServer(port, httpsPort); testServer.start(); - assertTrue("No value for https port", testServer.getRunningHttpsPort().isPresent()); + assertTrue(testServer.getRunningHttpsPort().isPresent(), "No value for https port"); assertTrue( - "The os provided https port is not greater than 0", - testServer.getRunningHttpsPort().getAsInt() > 0); - assertTrue("No value for http port", testServer.getRunningHttpPort().isPresent()); + testServer.getRunningHttpsPort().getAsInt() > 0, + "The os provided https port is not greater than 0"); + assertTrue(testServer.getRunningHttpPort().isPresent(), "No value for http port"); assertTrue( - "The os provided http port is not greater than 0", - testServer.getRunningHttpPort().getAsInt() > 0); + testServer.getRunningHttpPort().getAsInt() > 0, + "The os provided http port is not greater than 0"); testServer.stop(); } } diff --git a/web/play-java-forms/src/test/java/play/mvc/HttpFormsTest.java b/web/play-java-forms/src/test/java/play/mvc/HttpFormsTest.java index 415c0a6568e..ab3ed4809af 100644 --- a/web/play-java-forms/src/test/java/play/mvc/HttpFormsTest.java +++ b/web/play-java-forms/src/test/java/play/mvc/HttpFormsTest.java @@ -4,7 +4,7 @@ package play.mvc; -import static org.fest.assertions.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.*; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; @@ -14,7 +14,7 @@ import java.util.*; import java.util.function.Consumer; import javax.validation.ValidatorFactory; -import org.junit.Test; +import org.junit.jupiter.api.Test; import play.Application; import play.Environment; import play.api.i18n.DefaultLangs; @@ -59,7 +59,7 @@ private Form copyFormWithoutRawData(final Form formToCopy, final Appli null, formToCopy.errors(), formToCopy.value(), - (Class[]) null, + null, app.injector().instanceOf(MessagesApi.class), app.injector().instanceOf(Formatters.class), app.injector().instanceOf(ValidatorFactory.class), @@ -84,25 +84,23 @@ public void testLangDataBinder() { // Parse french input with french formatter Request req = rb.langCookie(Lang.forCode("fr"), Helpers.stubMessagesApi()).build(); Form myForm = formFactory.form(Money.class).bindFromRequest(req); - assertThat(myForm.hasErrors()).isFalse(); - assertThat(myForm.hasGlobalErrors()).isFalse(); + assertFalse(myForm.hasErrors()); + assertFalse(myForm.hasGlobalErrors()); Money money = myForm.get(); - assertThat(money.getAmount()).isEqualTo(new BigDecimal("1234567.89")); + assertEquals(new BigDecimal("1234567.89"), money.getAmount()); String amount = copyFormWithoutRawData(myForm, app).field("amount").value().get(); - assertThat(amount) - .isEqualTo( - amount.contains(" ") - ? "1 234 567,89" - : "1 234 567,89"); // Java 13+ uses different whitespaces + assertEquals( + amount.contains(" ") ? "1 234 567,89" : "1 234 567,89", + amount); // Java 13+ uses different whitespaces // Parse french input with english formatter req = rb.langCookie(Lang.forCode("en"), Helpers.stubMessagesApi()).build(); myForm = formFactory.form(Money.class).bindFromRequest(req); - assertThat(myForm.hasErrors()).isFalse(); - assertThat(myForm.hasGlobalErrors()).isFalse(); + assertFalse(myForm.hasErrors()); + assertFalse(myForm.hasGlobalErrors()); money = myForm.get(); - assertThat(money.getAmount()).isEqualTo(new BigDecimal("123456789")); - assertThat(copyFormWithoutRawData(myForm, app).field("amount").value().get()) - .isEqualTo("123,456,789"); + assertEquals(new BigDecimal("123456789"), money.getAmount()); + assertEquals( + "123,456,789", copyFormWithoutRawData(myForm, app).field("amount").value().get()); // Prepare Request with english number data = new HashMap<>(); @@ -111,25 +109,23 @@ public void testLangDataBinder() { // Parse english input with french formatter req = rb.langCookie(Lang.forCode("fr"), Helpers.stubMessagesApi()).build(); myForm = formFactory.form(Money.class).bindFromRequest(req); - assertThat(myForm.hasErrors()).isFalse(); - assertThat(myForm.hasGlobalErrors()).isFalse(); + assertFalse(myForm.hasErrors()); + assertFalse(myForm.hasGlobalErrors()); money = myForm.get(); - assertThat(money.getAmount()).isEqualTo(new BigDecimal("1234567")); + assertEquals(new BigDecimal("1234567"), money.getAmount()); amount = copyFormWithoutRawData(myForm, app).field("amount").value().get(); - assertThat(amount) - .isEqualTo( - amount.contains(" ") - ? "1 234 567" - : "1 234 567"); // Java 13+ uses different whitespaces + assertEquals( + amount.contains(" ") ? "1 234 567" : "1 234 567", + amount); // Java 13+ uses different whitespaces // Parse english input with english formatter req = rb.langCookie(Lang.forCode("en"), Helpers.stubMessagesApi()).build(); myForm = formFactory.form(Money.class).bindFromRequest(req); - assertThat(myForm.hasErrors()).isFalse(); - assertThat(myForm.hasGlobalErrors()).isFalse(); + assertFalse(myForm.hasErrors()); + assertFalse(myForm.hasGlobalErrors()); money = myForm.get(); - assertThat(money.getAmount()).isEqualTo(new BigDecimal("1234567.89")); - assertThat(copyFormWithoutRawData(myForm, app).field("amount").value().get()) - .isEqualTo("1,234,567.89"); + assertEquals(new BigDecimal("1234567.89"), money.getAmount()); + assertEquals( + "1,234,567.89", copyFormWithoutRawData(myForm, app).field("amount").value().get()); // Clean up (Actually not really necassary because formatters are not global anyway ;-) formatters.conversion.removeConvertible( @@ -156,25 +152,23 @@ public void testLangDataBinderTransient() { // Parse french input with french formatter Request req = rb.transientLang(Lang.forCode("fr")).build(); Form myForm = formFactory.form(Money.class).bindFromRequest(req); - assertThat(myForm.hasErrors()).isFalse(); - assertThat(myForm.hasGlobalErrors()).isFalse(); + assertFalse(myForm.hasErrors()); + assertFalse(myForm.hasGlobalErrors()); Money money = myForm.get(); - assertThat(money.getAmount()).isEqualTo(new BigDecimal("1234567.89")); + assertEquals(new BigDecimal("1234567.89"), money.getAmount()); String amount = copyFormWithoutRawData(myForm, app).field("amount").value().get(); - assertThat(amount) - .isEqualTo( - amount.contains(" ") - ? "1 234 567,89" - : "1 234 567,89"); // Java 13+ uses different whitespaces + assertEquals( + amount.contains(" ") ? "1 234 567,89" : "1 234 567,89", + amount); // Java 13+ uses different whitespaces // Parse french input with english formatter req = rb.transientLang(Lang.forCode("en")).build(); myForm = formFactory.form(Money.class).bindFromRequest(req); - assertThat(myForm.hasErrors()).isFalse(); - assertThat(myForm.hasGlobalErrors()).isFalse(); + assertFalse(myForm.hasErrors()); + assertFalse(myForm.hasGlobalErrors()); money = myForm.get(); - assertThat(money.getAmount()).isEqualTo(new BigDecimal("123456789")); - assertThat(copyFormWithoutRawData(myForm, app).field("amount").value().get()) - .isEqualTo("123,456,789"); + assertEquals(new BigDecimal("123456789"), money.getAmount()); + assertEquals( + "123,456,789", copyFormWithoutRawData(myForm, app).field("amount").value().get()); // Prepare Request with english number data = new HashMap<>(); @@ -183,25 +177,23 @@ public void testLangDataBinderTransient() { // Parse english input with french formatter req = rb.transientLang(Lang.forCode("fr")).build(); myForm = formFactory.form(Money.class).bindFromRequest(req); - assertThat(myForm.hasErrors()).isFalse(); - assertThat(myForm.hasGlobalErrors()).isFalse(); + assertFalse(myForm.hasErrors()); + assertFalse(myForm.hasGlobalErrors()); money = myForm.get(); - assertThat(money.getAmount()).isEqualTo(new BigDecimal("1234567")); + assertEquals(new BigDecimal("1234567"), money.getAmount()); amount = copyFormWithoutRawData(myForm, app).field("amount").value().get(); - assertThat(amount) - .isEqualTo( - amount.contains(" ") - ? "1 234 567" - : "1 234 567"); // Java 13+ uses different whitespaces + String expectedAmountEN = amount.contains(" ") ? "1 234 567" : "1 234 567"; + assertEquals(expectedAmountEN, amount); + // Parse english input with english formatter req = rb.transientLang(Lang.forCode("en")).build(); myForm = formFactory.form(Money.class).bindFromRequest(req); - assertThat(myForm.hasErrors()).isFalse(); - assertThat(myForm.hasGlobalErrors()).isFalse(); + assertFalse(myForm.hasErrors()); + assertFalse(myForm.hasGlobalErrors()); money = myForm.get(); - assertThat(money.getAmount()).isEqualTo(new BigDecimal("1234567.89")); - assertThat(copyFormWithoutRawData(myForm, app).field("amount").value().get()) - .isEqualTo("1,234,567.89"); + assertEquals(new BigDecimal("1234567.89"), money.getAmount()); + assertEquals( + "1,234,567.89", copyFormWithoutRawData(myForm, app).field("amount").value().get()); // Clean up (Actually not really necassary because formatters are not global anyway ;-) formatters.conversion.removeConvertible( @@ -244,8 +236,9 @@ public void testLangErrorsAsJson() { config, lang); - assertThat(form.errorsAsJson().get("foo").toString()) - .isEqualTo("[\"It looks like something was not correct\"]"); + assertEquals( + "[\"It looks like something was not correct\"]", + form.errorsAsJson().get("foo").toString()); }); } @@ -279,13 +272,14 @@ public void testErrorsAsJsonWithEmptyMessages() { Map data = new HashMap<>(); data.put( "amount", - "I am not a BigDecimal, I am a String that doesn't even represent a number! Binding to a BigDecimal will fail!"); - - assertThat( - form.bind(lang, new RequestBuilder().build().attrs(), data) - .errorsAsJson() - .toString()) - .isEqualTo("{\"amount\":[\"error.invalid\"]}"); + "I am not a BigDecimal, I am a String that doesn't even represent a number! Binding to a " + + "BigDecimal will fail!"); + + assertEquals( + "{\"amount\":[\"error.invalid\"]}", + form.bind(lang, new RequestBuilder().build().attrs(), data) + .errorsAsJson() + .toString()); }); } @@ -302,13 +296,14 @@ public void testLangAnnotationDateDataBinder() { // Parse date input with pattern from the default messages file Request req = rb.build(); Form myForm = formFactory.form(Birthday.class).bindFromRequest(req); - assertThat(myForm.hasErrors()).isFalse(); - assertThat(myForm.hasGlobalErrors()).isFalse(); + assertFalse(myForm.hasErrors()); + assertFalse(myForm.hasGlobalErrors()); Birthday birthday = myForm.get(); - assertThat(copyFormWithoutRawData(myForm, app).field("date").value().get()) - .isEqualTo("03/10/1986"); - assertThat(birthday.getDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate()) - .isEqualTo(LocalDate.of(1986, 10, 3)); + assertEquals( + "03/10/1986", copyFormWithoutRawData(myForm, app).field("date").value().get()); + assertEquals( + LocalDate.of(1986, 10, 3), + birthday.getDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate()); // Prepare Request data = new HashMap<>(); @@ -317,13 +312,14 @@ public void testLangAnnotationDateDataBinder() { // Parse french date input with pattern from the french messages file req = rb.langCookie(Lang.forCode("fr"), Helpers.stubMessagesApi()).build(); myForm = formFactory.form(Birthday.class).bindFromRequest(req); - assertThat(myForm.hasErrors()).isFalse(); - assertThat(myForm.hasGlobalErrors()).isFalse(); + assertFalse(myForm.hasErrors()); + assertFalse(myForm.hasGlobalErrors()); birthday = myForm.get(); - assertThat(copyFormWithoutRawData(myForm, app).field("date").value().get()) - .isEqualTo("16.02.2001"); - assertThat(birthday.getDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate()) - .isEqualTo(LocalDate.of(2001, 2, 16)); + assertEquals( + "16.02.2001", copyFormWithoutRawData(myForm, app).field("date").value().get()); + assertEquals( + LocalDate.of(2001, 2, 16), + birthday.getDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate()); // Prepare Request data = new HashMap<>(); @@ -332,13 +328,14 @@ public void testLangAnnotationDateDataBinder() { // Parse english date input with pattern from the en-US messages file req = rb.langCookie(Lang.forCode("en-US"), Helpers.stubMessagesApi()).build(); myForm = formFactory.form(Birthday.class).bindFromRequest(req); - assertThat(myForm.hasErrors()).isFalse(); - assertThat(myForm.hasGlobalErrors()).isFalse(); + assertFalse(myForm.hasErrors()); + assertFalse(myForm.hasGlobalErrors()); birthday = myForm.get(); - assertThat(copyFormWithoutRawData(myForm, app).field("date").value().get()) - .isEqualTo("08-31-1950"); - assertThat(birthday.getDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate()) - .isEqualTo(LocalDate.of(1950, 8, 31)); + assertEquals( + "08-31-1950", copyFormWithoutRawData(myForm, app).field("date").value().get()); + assertEquals( + LocalDate.of(1950, 8, 31), + birthday.getDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate()); }); } @@ -355,13 +352,14 @@ public void testLangAnnotationDateDataBinderTransient() { // Parse date input with pattern from the default messages file Request req = rb.build(); Form myForm = formFactory.form(Birthday.class).bindFromRequest(req); - assertThat(myForm.hasErrors()).isFalse(); - assertThat(myForm.hasGlobalErrors()).isFalse(); + assertFalse(myForm.hasErrors()); + assertFalse(myForm.hasGlobalErrors()); Birthday birthday = myForm.get(); - assertThat(copyFormWithoutRawData(myForm, app).field("date").value().get()) - .isEqualTo("03/10/1986"); - assertThat(birthday.getDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate()) - .isEqualTo(LocalDate.of(1986, 10, 3)); + assertEquals( + "03/10/1986", copyFormWithoutRawData(myForm, app).field("date").value().get()); + assertEquals( + LocalDate.of(1986, 10, 3), + birthday.getDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate()); // Prepare Request data = new HashMap<>(); @@ -370,13 +368,14 @@ public void testLangAnnotationDateDataBinderTransient() { // Parse french date input with pattern from the french messages file req = rb.transientLang(Lang.forCode("fr")).build(); myForm = formFactory.form(Birthday.class).bindFromRequest(req); - assertThat(myForm.hasErrors()).isFalse(); - assertThat(myForm.hasGlobalErrors()).isFalse(); + assertFalse(myForm.hasErrors()); + assertFalse(myForm.hasGlobalErrors()); birthday = myForm.get(); - assertThat(copyFormWithoutRawData(myForm, app).field("date").value().get()) - .isEqualTo("16.02.2001"); - assertThat(birthday.getDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate()) - .isEqualTo(LocalDate.of(2001, 2, 16)); + assertEquals( + "16.02.2001", copyFormWithoutRawData(myForm, app).field("date").value().get()); + assertEquals( + LocalDate.of(2001, 2, 16), + birthday.getDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate()); // Prepare Request data = new HashMap<>(); @@ -385,13 +384,14 @@ public void testLangAnnotationDateDataBinderTransient() { // Parse english date input with pattern from the en-US messages file req = rb.transientLang(Lang.forCode("en-US")).build(); myForm = formFactory.form(Birthday.class).bindFromRequest(req); - assertThat(myForm.hasErrors()).isFalse(); - assertThat(myForm.hasGlobalErrors()).isFalse(); + assertFalse(myForm.hasErrors()); + assertFalse(myForm.hasGlobalErrors()); birthday = myForm.get(); - assertThat(copyFormWithoutRawData(myForm, app).field("date").value().get()) - .isEqualTo("08-31-1950"); - assertThat(birthday.getDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate()) - .isEqualTo(LocalDate.of(1950, 8, 31)); + assertEquals( + "08-31-1950", copyFormWithoutRawData(myForm, app).field("date").value().get()); + assertEquals( + LocalDate.of(1950, 8, 31), + birthday.getDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate()); }); } @@ -408,18 +408,19 @@ public void testLangDateDataBinder() { // Parse date input with pattern from Play's default messages file Request req = rb.build(); Form myForm = formFactory.form(Birthday.class).bindFromRequest(req); - assertThat(myForm.hasErrors()).isFalse(); - assertThat(myForm.hasGlobalErrors()).isFalse(); + assertFalse(myForm.hasErrors()); + assertFalse(myForm.hasGlobalErrors()); Birthday birthday = myForm.get(); - assertThat(copyFormWithoutRawData(myForm, app).field("alternativeDate").value().get()) - .isEqualTo("1982-05-07"); - assertThat( - birthday - .getAlternativeDate() - .toInstant() - .atZone(ZoneId.systemDefault()) - .toLocalDate()) - .isEqualTo(LocalDate.of(1982, 5, 7)); + assertEquals( + "1982-05-07", + copyFormWithoutRawData(myForm, app).field("alternativeDate").value().get()); + assertEquals( + LocalDate.of(1982, 5, 7), + birthday + .getAlternativeDate() + .toInstant() + .atZone(ZoneId.systemDefault()) + .toLocalDate()); // Prepare Request data = new HashMap<>(); @@ -428,18 +429,19 @@ public void testLangDateDataBinder() { // Parse french date input with pattern from the french messages file req = rb.langCookie(Lang.forCode("fr"), Helpers.stubMessagesApi()).build(); myForm = formFactory.form(Birthday.class).bindFromRequest(req); - assertThat(myForm.hasErrors()).isFalse(); - assertThat(myForm.hasGlobalErrors()).isFalse(); + assertFalse(myForm.hasErrors()); + assertFalse(myForm.hasGlobalErrors()); birthday = myForm.get(); - assertThat(copyFormWithoutRawData(myForm, app).field("alternativeDate").value().get()) - .isEqualTo("10_04_2005"); - assertThat( - birthday - .getAlternativeDate() - .toInstant() - .atZone(ZoneId.systemDefault()) - .toLocalDate()) - .isEqualTo(LocalDate.of(2005, 10, 4)); + assertEquals( + "10_04_2005", + copyFormWithoutRawData(myForm, app).field("alternativeDate").value().get()); + assertEquals( + LocalDate.of(2005, 10, 4), + birthday + .getAlternativeDate() + .toInstant() + .atZone(ZoneId.systemDefault()) + .toLocalDate()); // Prepare Request data = new HashMap<>(); @@ -448,18 +450,19 @@ public void testLangDateDataBinder() { // Parse english date input with pattern from the en-US messages file req = rb.langCookie(Lang.forCode("en-US"), Helpers.stubMessagesApi()).build(); myForm = formFactory.form(Birthday.class).bindFromRequest(req); - assertThat(myForm.hasErrors()).isFalse(); - assertThat(myForm.hasGlobalErrors()).isFalse(); + assertFalse(myForm.hasErrors()); + assertFalse(myForm.hasGlobalErrors()); birthday = myForm.get(); - assertThat(copyFormWithoutRawData(myForm, app).field("alternativeDate").value().get()) - .isEqualTo("03/12/1962"); - assertThat( - birthday - .getAlternativeDate() - .toInstant() - .atZone(ZoneId.systemDefault()) - .toLocalDate()) - .isEqualTo(LocalDate.of(1962, 12, 3)); + assertEquals( + "03/12/1962", + copyFormWithoutRawData(myForm, app).field("alternativeDate").value().get()); + assertEquals( + LocalDate.of(1962, 12, 3), + birthday + .getAlternativeDate() + .toInstant() + .atZone(ZoneId.systemDefault()) + .toLocalDate()); }); } @@ -476,18 +479,19 @@ public void testLangDateDataBinderTransient() { // Parse date input with pattern from Play's default messages file Request req = rb.build(); Form myForm = formFactory.form(Birthday.class).bindFromRequest(req); - assertThat(myForm.hasErrors()).isFalse(); - assertThat(myForm.hasGlobalErrors()).isFalse(); + assertFalse(myForm.hasErrors()); + assertFalse(myForm.hasGlobalErrors()); Birthday birthday = myForm.get(); - assertThat(copyFormWithoutRawData(myForm, app).field("alternativeDate").value().get()) - .isEqualTo("1982-05-07"); - assertThat( - birthday - .getAlternativeDate() - .toInstant() - .atZone(ZoneId.systemDefault()) - .toLocalDate()) - .isEqualTo(LocalDate.of(1982, 5, 7)); + assertEquals( + "1982-05-07", + copyFormWithoutRawData(myForm, app).field("alternativeDate").value().get()); + assertEquals( + LocalDate.of(1982, 5, 7), + birthday + .getAlternativeDate() + .toInstant() + .atZone(ZoneId.systemDefault()) + .toLocalDate()); // Prepare Request data = new HashMap<>(); @@ -496,18 +500,19 @@ public void testLangDateDataBinderTransient() { // Parse french date input with pattern from the french messages file req = rb.transientLang(Lang.forCode("fr")).build(); myForm = formFactory.form(Birthday.class).bindFromRequest(req); - assertThat(myForm.hasErrors()).isFalse(); - assertThat(myForm.hasGlobalErrors()).isFalse(); + assertFalse(myForm.hasErrors()); + assertFalse(myForm.hasGlobalErrors()); birthday = myForm.get(); - assertThat(copyFormWithoutRawData(myForm, app).field("alternativeDate").value().get()) - .isEqualTo("10_04_2005"); - assertThat( - birthday - .getAlternativeDate() - .toInstant() - .atZone(ZoneId.systemDefault()) - .toLocalDate()) - .isEqualTo(LocalDate.of(2005, 10, 4)); + assertEquals( + "10_04_2005", + copyFormWithoutRawData(myForm, app).field("alternativeDate").value().get()); + assertEquals( + LocalDate.of(2005, 10, 4), + birthday + .getAlternativeDate() + .toInstant() + .atZone(ZoneId.systemDefault()) + .toLocalDate()); // Prepare Request data = new HashMap<>(); @@ -516,18 +521,19 @@ public void testLangDateDataBinderTransient() { // Parse english date input with pattern from the en-US messages file req = rb.transientLang(Lang.forCode("en-US")).build(); myForm = formFactory.form(Birthday.class).bindFromRequest(req); - assertThat(myForm.hasErrors()).isFalse(); - assertThat(myForm.hasGlobalErrors()).isFalse(); + assertFalse(myForm.hasErrors()); + assertFalse(myForm.hasGlobalErrors()); birthday = myForm.get(); - assertThat(copyFormWithoutRawData(myForm, app).field("alternativeDate").value().get()) - .isEqualTo("03/12/1962"); - assertThat( - birthday - .getAlternativeDate() - .toInstant() - .atZone(ZoneId.systemDefault()) - .toLocalDate()) - .isEqualTo(LocalDate.of(1962, 12, 3)); + assertEquals( + "03/12/1962", + copyFormWithoutRawData(myForm, app).field("alternativeDate").value().get()); + assertEquals( + LocalDate.of(1962, 12, 3), + birthday + .getAlternativeDate() + .toInstant() + .atZone(ZoneId.systemDefault()) + .toLocalDate()); }); } @@ -546,14 +552,13 @@ public void testInvalidMessages() { // Parse date input with pattern from the default messages file Request req = rb.build(); Form myForm = formFactory.form(Task.class).bindFromRequest(req); - assertThat(myForm.hasErrors()).isTrue(); - assertThat(myForm.hasGlobalErrors()).isFalse(); - assertThat(myForm.error("dueDate").get().messages().size()).isEqualTo(2); - assertThat(myForm.error("dueDate").get().messages().get(0)).isEqualTo("error.invalid"); - assertThat(myForm.error("dueDate").get().messages().get(1)) - .isEqualTo("error.invalid.java.util.Date"); - assertThat(myForm.error("dueDate").get().message()) - .isEqualTo("error.invalid.java.util.Date"); + assertTrue(myForm.hasErrors()); + assertFalse(myForm.hasGlobalErrors()); + assertEquals(2, myForm.error("dueDate").get().messages().size()); + assertEquals("error.invalid", myForm.error("dueDate").get().messages().get(0)); + assertEquals( + "error.invalid.java.util.Date", myForm.error("dueDate").get().messages().get(1)); + assertEquals("error.invalid.java.util.Date", myForm.error("dueDate").get().message()); // Prepare Request data = new HashMap<>(); @@ -564,15 +569,14 @@ public void testInvalidMessages() { req = rb.langCookie(Lang.forCode("fr"), Helpers.stubMessagesApi()).build(); // Parse date input with pattern from the french messages file myForm = formFactory.form(Task.class).bindFromRequest(req); - assertThat(myForm.hasErrors()).isTrue(); - assertThat(myForm.hasGlobalErrors()).isFalse(); - assertThat(myForm.error("dueDate").get().messages().size()).isEqualTo(3); - assertThat(myForm.error("dueDate").get().messages().get(0)).isEqualTo("error.invalid"); - assertThat(myForm.error("dueDate").get().messages().get(1)) - .isEqualTo("error.invalid.java.util.Date"); - assertThat(myForm.error("dueDate").get().messages().get(2)) - .isEqualTo("error.invalid.dueDate"); - assertThat(myForm.error("dueDate").get().message()).isEqualTo("error.invalid.dueDate"); + assertTrue(myForm.hasErrors()); + assertFalse(myForm.hasGlobalErrors()); + assertEquals(3, myForm.error("dueDate").get().messages().size()); + assertEquals("error.invalid", myForm.error("dueDate").get().messages().get(0)); + assertEquals( + "error.invalid.java.util.Date", myForm.error("dueDate").get().messages().get(1)); + assertEquals("error.invalid.dueDate", myForm.error("dueDate").get().messages().get(2)); + assertEquals("error.invalid.dueDate", myForm.error("dueDate").get().message()); }); } @@ -593,8 +597,8 @@ public void testConstraintWithInjectedMessagesApi() { // Parse input with pattern from the default messages file Request req = rb.build(); Form myForm = formFactory.form(Task.class).bindFromRequest(req); - assertThat(myForm.hasErrors()).isFalse(); - assertThat(myForm.hasGlobalErrors()).isFalse(); + assertFalse(myForm.hasErrors()); + assertFalse(myForm.hasGlobalErrors()); // Prepare Request data = new HashMap<>(); @@ -607,8 +611,8 @@ public void testConstraintWithInjectedMessagesApi() { // Parse input with pattern from the french messages file req = rb.langCookie(Lang.forCode("fr"), Helpers.stubMessagesApi()).build(); myForm = formFactory.form(Task.class).bindFromRequest(req); - assertThat(myForm.hasErrors()).isFalse(); - assertThat(myForm.hasGlobalErrors()).isFalse(); + assertFalse(myForm.hasErrors()); + assertFalse(myForm.hasGlobalErrors()); // Prepare Request data = new HashMap<>(); @@ -621,13 +625,12 @@ public void testConstraintWithInjectedMessagesApi() { // Parse WRONG input with pattern from the french messages file req = rb.langCookie(Lang.forCode("fr"), Helpers.stubMessagesApi()).build(); myForm = formFactory.form(Task.class).bindFromRequest(req); - assertThat(myForm.hasErrors()).isTrue(); - assertThat(myForm.hasGlobalErrors()).isFalse(); - assertThat(myForm.error("zip").get().messages().size()).isEqualTo(1); - assertThat(myForm.error("zip").get().message()).isEqualTo("error.i18nconstraint"); - assertThat(myForm.error("anotherZip").get().messages().size()).isEqualTo(1); - assertThat(myForm.error("anotherZip").get().message()) - .isEqualTo("error.anotheri18nconstraint"); + assertTrue(myForm.hasErrors()); + assertFalse(myForm.hasGlobalErrors()); + assertEquals(1, myForm.error("zip").get().messages().size()); + assertEquals("error.i18nconstraint", myForm.error("zip").get().message()); + assertEquals(1, myForm.error("anotherZip").get().messages().size()); + assertEquals("error.anotheri18nconstraint", myForm.error("anotherZip").get().message()); }); } } diff --git a/web/play-java-forms/src/test/scala/play/data/format/FormattersTest.java b/web/play-java-forms/src/test/scala/play/data/format/FormattersTest.java index 8075084f911..0dc13f7cabd 100644 --- a/web/play-java-forms/src/test/scala/play/data/format/FormattersTest.java +++ b/web/play-java-forms/src/test/scala/play/data/format/FormattersTest.java @@ -4,8 +4,8 @@ package play.data.format; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; @@ -14,13 +14,13 @@ import java.text.ParseException; import java.util.Locale; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; public class FormattersTest { private Formatters formatters; - @Before + @BeforeEach public void prepareFormatters() { formatters = new Formatters(null); formatters.register(Integer.class, new IntegerFormatter()); From 26b4c74f74d3205933f215ceeb18bf11a25c5aa4 Mon Sep 17 00:00:00 2001 From: "H. Habighorst" Date: Fri, 9 Jun 2023 20:40:50 +0200 Subject: [PATCH 02/15] #11839: Break up play-test, add basic JUnit 5 extensions --- build.sbt | 32 +++++++++++- project/Dependencies.scala | 4 +- .../play/test/junit4}/WithApplication.java | 3 +- .../java/play/test/junit4}/WithBrowser.java | 4 +- .../java/play/test/junit4}/WithServer.java | 4 +- .../junit4}/WithApplicationOverrideTest.java | 2 +- .../test/junit4}/WithApplicationTest.java | 2 +- .../play/test/junit4}/WithBrowserTest.java | 2 +- .../src/test/resources/logback-test.xml | 28 +++++++++++ .../test/junit5/ApplicationExtension.java | 43 ++++++++++++++++ .../test/junit5/BrowserServerExtension.java | 49 +++++++++++++++++++ .../ApplicationExtensionOverrideTest.java | 37 ++++++++++++++ .../junit5/BrowserServerExtensionTest.java | 29 +++++++++++ .../java/play/test/junit5}/HelpersTest.java | 39 ++++++++------- .../play/test/junit5}/TestServerTest.java | 10 ++-- .../src/test/resources/logback-test.xml | 28 +++++++++++ .../src/main/java/play/test/TestBrowser.java | 2 +- 17 files changed, 283 insertions(+), 35 deletions(-) rename testkit/{play-test/src/main/java/play/test => play-test-junit4/src/main/java/play/test/junit4}/WithApplication.java (96%) rename testkit/{play-test/src/main/java/play/test => play-test-junit4/src/main/java/play/test/junit4}/WithBrowser.java (93%) rename testkit/{play-test/src/main/java/play/test => play-test-junit4/src/main/java/play/test/junit4}/WithServer.java (95%) rename testkit/{play-test/src/test/java/play/test => play-test-junit4/src/test/java/play/test/junit4}/WithApplicationOverrideTest.java (97%) rename testkit/{play-test/src/test/java/play/test => play-test-junit4/src/test/java/play/test/junit4}/WithApplicationTest.java (96%) rename testkit/{play-test/src/test/java/play/test => play-test-junit4/src/test/java/play/test/junit4}/WithBrowserTest.java (95%) create mode 100644 testkit/play-test-junit4/src/test/resources/logback-test.xml create mode 100644 testkit/play-test-junit5/src/main/java/play/test/junit5/ApplicationExtension.java create mode 100644 testkit/play-test-junit5/src/main/java/play/test/junit5/BrowserServerExtension.java create mode 100644 testkit/play-test-junit5/src/test/java/play/test/junit5/ApplicationExtensionOverrideTest.java create mode 100644 testkit/play-test-junit5/src/test/java/play/test/junit5/BrowserServerExtensionTest.java rename testkit/{play-test/src/test/java/play/test => play-test-junit5/src/test/java/play/test/junit5}/HelpersTest.java (81%) rename testkit/{play-test/src/test/java/play/test => play-test-junit5/src/test/java/play/test/junit5}/TestServerTest.java (89%) create mode 100644 testkit/play-test-junit5/src/test/resources/logback-test.xml diff --git a/build.sbt b/build.sbt index 27e84f442fc..cc3882aedb4 100644 --- a/build.sbt +++ b/build.sbt @@ -188,7 +188,7 @@ lazy val PlayJpaProject = PlayCrossBuiltProject("Play-Java-JPA", "persistence/pl lazy val PlayTestProject = PlayCrossBuiltProject("Play-Test", "testkit/play-test") .settings( - libraryDependencies ++= testDependencies ++ Seq(h2database % "test"), + libraryDependencies ++= testDependencies ++ Seq(h2database % Test), (Test / parallelExecution) := false ) .dependsOn( @@ -196,7 +196,35 @@ lazy val PlayTestProject = PlayCrossBuiltProject("Play-Test", "testkit/play-test PlayServerProject, // We still need a server provider when running Play-Test tests. // Since Akka HTTP is the default, we should use it here. - PlayAkkaHttpServerProject % "test" + PlayAkkaHttpServerProject % Test + ) + +lazy val PlayTestJUnit4Project = PlayCrossBuiltProject("Play-Test-JUnit4", "testkit/play-test-junit4") + .settings( + libraryDependencies ++= Seq(junit4, junit4Interface), + libraryDependencies --= Seq(junit5, junit5Interface), + (Test / parallelExecution) := false + ) + .dependsOn( + PlayGuiceProject, + PlayServerProject, + // We still need a server provider when running Play-Test tests. + // Since Akka HTTP is the default, we should use it here. + PlayAkkaHttpServerProject % Test, + PlayTestProject + ) + +lazy val PlayTestJUnit5Project = PlayCrossBuiltProject("Play-Test-JUnit5", "testkit/play-test-junit5") + .settings( + (Test / parallelExecution) := false + ) + .dependsOn( + PlayGuiceProject, + PlayServerProject, + // We still need a server provider when running Play-Test tests. + // Since Akka HTTP is the default, we should use it here. + PlayAkkaHttpServerProject % Test, + PlayTestProject ) lazy val PlaySpecs2Project = PlayCrossBuiltProject("Play-Specs2", "testkit/play-specs2") diff --git a/project/Dependencies.scala b/project/Dependencies.scala index 09fb402c8e5..9db60bf2661 100644 --- a/project/Dependencies.scala +++ b/project/Dependencies.scala @@ -157,8 +157,6 @@ object Dependencies { val junit5Interface = "net.aichler" % "jupiter-interface" % "0.11.1" val javaTestDeps = Seq( - junit4, - junit4Interface, junit5, junit5Interface, mockitoAll, @@ -281,7 +279,7 @@ object Dependencies { // See https://repo1.maven.org/maven2/io/fluentlenium/fluentlenium-parent/6.0.0/fluentlenium-parent-6.0.0.pom val seleniumVersion = "4.9.1" - val testDependencies = Seq(junit4, junit4Interface, junit5, junit5Interface, guava, logback) ++ Seq( + val testDependencies = Seq(junit5, junit5Interface, guava, logback) ++ Seq( ("io.fluentlenium" % "fluentlenium-core" % fluentleniumVersion).exclude("org.jboss.netty", "netty"), // htmlunit-driver uses an open range to selenium dependencies. This is slightly // slowing down the build. So the open range deps were removed and we can re-add diff --git a/testkit/play-test/src/main/java/play/test/WithApplication.java b/testkit/play-test-junit4/src/main/java/play/test/junit4/WithApplication.java similarity index 96% rename from testkit/play-test/src/main/java/play/test/WithApplication.java rename to testkit/play-test-junit4/src/main/java/play/test/junit4/WithApplication.java index 374cd614a02..6183ac85610 100644 --- a/testkit/play-test/src/main/java/play/test/WithApplication.java +++ b/testkit/play-test-junit4/src/main/java/play/test/junit4/WithApplication.java @@ -2,12 +2,13 @@ * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. */ -package play.test; +package play.test.junit4; import akka.stream.Materializer; import org.junit.After; import org.junit.Before; import play.Application; +import play.test.Helpers; /** * Provides an application for JUnit tests. Make your test class extend this class and an diff --git a/testkit/play-test/src/main/java/play/test/WithBrowser.java b/testkit/play-test-junit4/src/main/java/play/test/junit4/WithBrowser.java similarity index 93% rename from testkit/play-test/src/main/java/play/test/WithBrowser.java rename to testkit/play-test-junit4/src/main/java/play/test/junit4/WithBrowser.java index 4f8b392ac6a..96644e38899 100644 --- a/testkit/play-test/src/main/java/play/test/WithBrowser.java +++ b/testkit/play-test-junit4/src/main/java/play/test/junit4/WithBrowser.java @@ -2,10 +2,12 @@ * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. */ -package play.test; +package play.test.junit4; import org.junit.After; import org.junit.Before; +import play.test.Helpers; +import play.test.TestBrowser; /** * Provides a server and browser to JUnit tests. Make your test class extend this class and an diff --git a/testkit/play-test/src/main/java/play/test/WithServer.java b/testkit/play-test-junit4/src/main/java/play/test/junit4/WithServer.java similarity index 95% rename from testkit/play-test/src/main/java/play/test/WithServer.java rename to testkit/play-test-junit4/src/main/java/play/test/junit4/WithServer.java index 81dec621035..44106cc9e0d 100644 --- a/testkit/play-test/src/main/java/play/test/WithServer.java +++ b/testkit/play-test-junit4/src/main/java/play/test/junit4/WithServer.java @@ -2,11 +2,13 @@ * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. */ -package play.test; +package play.test.junit4; import org.junit.After; import org.junit.Before; import play.Application; +import play.test.Helpers; +import play.test.TestServer; /** * Provides a server to JUnit tests. Make your test class extend this class and an HTTP server will diff --git a/testkit/play-test/src/test/java/play/test/WithApplicationOverrideTest.java b/testkit/play-test-junit4/src/test/java/play/test/junit4/WithApplicationOverrideTest.java similarity index 97% rename from testkit/play-test/src/test/java/play/test/WithApplicationOverrideTest.java rename to testkit/play-test-junit4/src/test/java/play/test/junit4/WithApplicationOverrideTest.java index 60e127e838b..44f9c2e93af 100644 --- a/testkit/play-test/src/test/java/play/test/WithApplicationOverrideTest.java +++ b/testkit/play-test-junit4/src/test/java/play/test/junit4/WithApplicationOverrideTest.java @@ -2,7 +2,7 @@ * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. */ -package play.test; +package play.test.junit4; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; diff --git a/testkit/play-test/src/test/java/play/test/WithApplicationTest.java b/testkit/play-test-junit4/src/test/java/play/test/junit4/WithApplicationTest.java similarity index 96% rename from testkit/play-test/src/test/java/play/test/WithApplicationTest.java rename to testkit/play-test-junit4/src/test/java/play/test/junit4/WithApplicationTest.java index ed743580d0b..d1c901504ce 100644 --- a/testkit/play-test/src/test/java/play/test/WithApplicationTest.java +++ b/testkit/play-test-junit4/src/test/java/play/test/junit4/WithApplicationTest.java @@ -2,7 +2,7 @@ * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. */ -package play.test; +package play.test.junit4; import static org.junit.Assert.assertNotNull; diff --git a/testkit/play-test/src/test/java/play/test/WithBrowserTest.java b/testkit/play-test-junit4/src/test/java/play/test/junit4/WithBrowserTest.java similarity index 95% rename from testkit/play-test/src/test/java/play/test/WithBrowserTest.java rename to testkit/play-test-junit4/src/test/java/play/test/junit4/WithBrowserTest.java index f5d70ad2f71..1a4a4791177 100644 --- a/testkit/play-test/src/test/java/play/test/WithBrowserTest.java +++ b/testkit/play-test-junit4/src/test/java/play/test/junit4/WithBrowserTest.java @@ -2,7 +2,7 @@ * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. */ -package play.test; +package play.test.junit4; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.MatcherAssert.assertThat; diff --git a/testkit/play-test-junit4/src/test/resources/logback-test.xml b/testkit/play-test-junit4/src/test/resources/logback-test.xml new file mode 100644 index 00000000000..1f4fdac4cc1 --- /dev/null +++ b/testkit/play-test-junit4/src/test/resources/logback-test.xml @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + + + %level %logger{15} - %message%n%ex{short} + + + + + + + + diff --git a/testkit/play-test-junit5/src/main/java/play/test/junit5/ApplicationExtension.java b/testkit/play-test-junit5/src/main/java/play/test/junit5/ApplicationExtension.java new file mode 100644 index 00000000000..2201ac32324 --- /dev/null +++ b/testkit/play-test-junit5/src/main/java/play/test/junit5/ApplicationExtension.java @@ -0,0 +1,43 @@ +/* + * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. + */ + +package play.test.junit5; + +import akka.stream.Materializer; +import java.util.Objects; +import org.junit.jupiter.api.extension.AfterAllCallback; +import org.junit.jupiter.api.extension.BeforeAllCallback; +import org.junit.jupiter.api.extension.ExtensionContext; +import play.Application; +import play.test.Helpers; + +public class ApplicationExtension implements BeforeAllCallback, AfterAllCallback { + private final Application application; + + public ApplicationExtension(Application application) { + this.application = application; + } + + public Application getApplication() { + return application; + } + + public Materializer getMaterializer() { + return application.asScala().materializer(); + } + + @Override + public void afterAll(ExtensionContext context) { + if (Objects.nonNull(application)) { + Helpers.stop(application); + } + } + + @Override + public void beforeAll(ExtensionContext context) { + if (Objects.nonNull(application)) { + Helpers.start(application); + } + } +} diff --git a/testkit/play-test-junit5/src/main/java/play/test/junit5/BrowserServerExtension.java b/testkit/play-test-junit5/src/main/java/play/test/junit5/BrowserServerExtension.java new file mode 100644 index 00000000000..9963da7ccb2 --- /dev/null +++ b/testkit/play-test-junit5/src/main/java/play/test/junit5/BrowserServerExtension.java @@ -0,0 +1,49 @@ +/* + * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. + */ + +package play.test.junit5; + +import java.util.Objects; + +import org.junit.jupiter.api.extension.AfterAllCallback; +import org.junit.jupiter.api.extension.BeforeAllCallback; +import org.junit.jupiter.api.extension.ExtensionContext; +import play.test.TestBrowser; +import play.test.TestServer; + +public class BrowserServerExtension implements BeforeAllCallback, AfterAllCallback { + + private final TestBrowser testBrowser; + private final TestServer testServer; + + public BrowserServerExtension(TestBrowser testBrowser, TestServer testServer) { + this.testBrowser = testBrowser; + this.testServer = testServer; + } + + public TestBrowser getTestBrowser() { + return testBrowser; + } + + public TestServer getTestServer() { + return testServer; + } + + @Override + public void afterAll(ExtensionContext context) { + if (Objects.nonNull(testServer)) { + testServer.stop(); + } + if (Objects.nonNull(testBrowser)) { + testBrowser.quit(); + } + } + + @Override + public void beforeAll(ExtensionContext context) { + if (Objects.nonNull(testServer)) { + testServer.start(); + } + } +} diff --git a/testkit/play-test-junit5/src/test/java/play/test/junit5/ApplicationExtensionOverrideTest.java b/testkit/play-test-junit5/src/test/java/play/test/junit5/ApplicationExtensionOverrideTest.java new file mode 100644 index 00000000000..4bf6efa5c1c --- /dev/null +++ b/testkit/play-test-junit5/src/test/java/play/test/junit5/ApplicationExtensionOverrideTest.java @@ -0,0 +1,37 @@ +/* + * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. + */ + +package play.test.junit5; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import play.inject.guice.GuiceApplicationBuilder; + +class ApplicationExtensionOverrideTest { + @RegisterExtension + static ApplicationExtension applicationExtension = + new ApplicationExtension( + new GuiceApplicationBuilder().configure("extraConfig", "valueForExtraConfig").build() + ); + + @Test + void shouldHaveAnAppInstantiated() { + assertNotNull(applicationExtension.getApplication()); + } + + @Test + void shouldHaveAMaterializerInstantiated() { + assertNotNull(applicationExtension.getMaterializer()); + } + + @Test + void shouldHaveExtraConfiguration() { + assertEquals( + "valueForExtraConfig", + applicationExtension.getApplication().config().getString("extraConfig")); + } +} diff --git a/testkit/play-test-junit5/src/test/java/play/test/junit5/BrowserServerExtensionTest.java b/testkit/play-test-junit5/src/test/java/play/test/junit5/BrowserServerExtensionTest.java new file mode 100644 index 00000000000..5716ac4b937 --- /dev/null +++ b/testkit/play-test-junit5/src/test/java/play/test/junit5/BrowserServerExtensionTest.java @@ -0,0 +1,29 @@ +/* + * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. + */ + +package play.test.junit5; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import play.test.Helpers; +import play.test.TestBrowser; + +class BrowserServerExtensionTest { + @RegisterExtension + static BrowserServerExtension browserServer = + new BrowserServerExtension(Helpers.testBrowser(8080), Helpers.testServer(8080, Helpers.fakeApplication())); + + @Test + void withBrowserShouldProvideABrowser() { + TestBrowser browser = browserServer.getTestBrowser(); + + assertNotNull(browser); + browser.goTo("/"); + assertNotNull(browser.pageSource()); + assertTrue(browser.pageSource().contains("Action Not Found")); + } +} diff --git a/testkit/play-test/src/test/java/play/test/HelpersTest.java b/testkit/play-test-junit5/src/test/java/play/test/junit5/HelpersTest.java similarity index 81% rename from testkit/play-test/src/test/java/play/test/HelpersTest.java rename to testkit/play-test-junit5/src/test/java/play/test/junit5/HelpersTest.java index 7e2b4b79bd8..81e3835e561 100644 --- a/testkit/play-test/src/test/java/play/test/HelpersTest.java +++ b/testkit/play-test-junit5/src/test/java/play/test/junit5/HelpersTest.java @@ -2,7 +2,7 @@ * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. */ -package play.test; +package play.test.junit5; import static org.junit.jupiter.api.Assertions.*; import static play.test.Helpers.POST; @@ -19,50 +19,51 @@ import play.mvc.Http; import play.mvc.Result; import play.mvc.Results; +import play.test.Helpers; import play.twirl.api.Content; import play.twirl.api.Html; import scala.concurrent.Await; import scala.concurrent.Future; import scala.concurrent.duration.Duration; -public class HelpersTest { + class HelpersTest { @Test - public void shouldCreateASimpleFakeRequest() { + void shouldCreateASimpleFakeRequest() { Http.RequestImpl request = Helpers.fakeRequest().build(); assertEquals("GET", request.method()); assertEquals("/", request.path()); } @Test - public void shouldCreateAFakeRequestWithMethodAndUri() { + void shouldCreateAFakeRequestWithMethodAndUri() { Http.RequestImpl request = Helpers.fakeRequest("POST", "/my-uri").build(); assertEquals("POST", request.method()); assertEquals("/my-uri", request.path()); } @Test - public void shouldAddHostHeaderToFakeRequests() { + void shouldAddHostHeaderToFakeRequests() { Http.RequestImpl request = Helpers.fakeRequest().build(); assertEquals("localhost", request.host()); } @Test - public void shouldCreateFakeApplicationsWithAnInMemoryDatabase() { + void shouldCreateFakeApplicationsWithAnInMemoryDatabase() { Application application = Helpers.fakeApplication(Helpers.inMemoryDatabase()); assertNotNull(application.config().getString("db.default.driver")); assertNotNull(application.config().getString("db.default.url")); } @Test - public void shouldCreateFakeApplicationsWithAnNamedInMemoryDatabase() { + void shouldCreateFakeApplicationsWithAnNamedInMemoryDatabase() { Application application = Helpers.fakeApplication(Helpers.inMemoryDatabase("testDb")); assertNotNull(application.config().getString("db.testDb.driver")); assertNotNull(application.config().getString("db.testDb.url")); } @Test - public void shouldCreateFakeApplicationsWithAnNamedInMemoryDatabaseAndConnectionOptions() { + void shouldCreateFakeApplicationsWithAnNamedInMemoryDatabaseAndConnectionOptions() { Map options = new HashMap<>(); options.put("username", "testUsername"); options.put("ttl", "10"); @@ -75,14 +76,14 @@ public void shouldCreateFakeApplicationsWithAnNamedInMemoryDatabaseAndConnection } @Test - public void shouldExtractContentAsBytesFromAResult() { + void shouldExtractContentAsBytesFromAResult() { Result result = Results.ok("Test content"); ByteString contentAsBytes = Helpers.contentAsBytes(result); assertEquals(ByteString.fromString("Test content"), contentAsBytes); } @Test - public void shouldExtractContentAsBytesFromAResultUsingAMaterializer() throws Exception { + void shouldExtractContentAsBytesFromAResultUsingAMaterializer() throws Exception { ActorSystem actorSystem = ActorSystem.create("TestSystem"); try { @@ -98,28 +99,28 @@ public void shouldExtractContentAsBytesFromAResultUsingAMaterializer() throws Ex } @Test - public void shouldExtractContentAsBytesFromTwirlContent() { + void shouldExtractContentAsBytesFromTwirlContent() { Content content = Html.apply("Test content"); ByteString contentAsBytes = Helpers.contentAsBytes(content); assertEquals(ByteString.fromString("Test content"), contentAsBytes); } @Test - public void shouldExtractContentAsStringFromTwirlContent() { + void shouldExtractContentAsStringFromTwirlContent() { Content content = Html.apply("Test content"); String contentAsString = Helpers.contentAsString(content); assertEquals("Test content", contentAsString); } @Test - public void shouldExtractContentAsStringFromAResult() { + void shouldExtractContentAsStringFromAResult() { Result result = Results.ok("Test content"); String contentAsString = Helpers.contentAsString(result); assertEquals("Test content", contentAsString); } @Test - public void shouldExtractContentAsStringFromAResultUsingAMaterializer() throws Exception { + void shouldExtractContentAsStringFromAResultUsingAMaterializer() throws Exception { ActorSystem actorSystem = ActorSystem.create("TestSystem"); try { @@ -135,7 +136,7 @@ public void shouldExtractContentAsStringFromAResultUsingAMaterializer() throws E } @Test - public void shouldSuccessfullyExecutePostRequestWithEmptyBody() { + void shouldSuccessfullyExecutePostRequestWithEmptyBody() { Http.RequestBuilder request = Helpers.fakeRequest("POST", "/uri"); Application app = Helpers.fakeApplication(); @@ -144,7 +145,7 @@ public void shouldSuccessfullyExecutePostRequestWithEmptyBody() { } @Test - public void shouldSuccessfullyExecutePostRequestWithMultipartFormData() { + void shouldSuccessfullyExecutePostRequestWithMultipartFormData() { Application app = Helpers.fakeApplication(); Map postParams = new java.util.HashMap<>(); postParams.put("key", new String[] {"value"}); @@ -155,14 +156,14 @@ public void shouldSuccessfullyExecutePostRequestWithMultipartFormData() { } @Test - public void shouldReturnProperHasBodyValueForFakeRequest() { + void shouldReturnProperHasBodyValueForFakeRequest() { // Does not set a Content-Length and also not a Transfer-Encoding header, sets null as body Http.Request request = Helpers.fakeRequest("POST", "/uri").build(); assertFalse(request.hasBody()); } @Test - public void shouldReturnProperHasBodyValueForEmptyRawBuffer() { + void shouldReturnProperHasBodyValueForEmptyRawBuffer() { // Does set a Content-Length header Http.Request request = Helpers.fakeRequest("POST", "/uri").bodyRaw(ByteString.emptyByteString()).build(); @@ -170,7 +171,7 @@ public void shouldReturnProperHasBodyValueForEmptyRawBuffer() { } @Test - public void shouldReturnProperHasBodyValueForNonEmptyRawBuffer() { + void shouldReturnProperHasBodyValueForNonEmptyRawBuffer() { // Does set a Content-Length header Http.Request request = Helpers.fakeRequest("POST", "/uri").bodyRaw(ByteString.fromString("a")).build(); diff --git a/testkit/play-test/src/test/java/play/test/TestServerTest.java b/testkit/play-test-junit5/src/test/java/play/test/junit5/TestServerTest.java similarity index 89% rename from testkit/play-test/src/test/java/play/test/TestServerTest.java rename to testkit/play-test-junit5/src/test/java/play/test/junit5/TestServerTest.java index 65177466c78..5c8f5433285 100644 --- a/testkit/play-test/src/test/java/play/test/TestServerTest.java +++ b/testkit/play-test-junit5/src/test/java/play/test/junit5/TestServerTest.java @@ -2,16 +2,18 @@ * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. */ -package play.test; +package play.test.junit5; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; +import play.test.Helpers; +import play.test.TestServer; -public class TestServerTest { +class TestServerTest { @Test - public void shouldReturnHttpPort() { + void shouldReturnHttpPort() { int testServerPort = play.api.test.Helpers.testServerPort(); final TestServer testServer = Helpers.testServer(testServerPort); testServer.start(); @@ -26,7 +28,7 @@ public void shouldReturnHttpPort() { } @Test - public void shouldReturnHttpAndHttpsPorts() { + void shouldReturnHttpAndHttpsPorts() { int port = play.api.test.Helpers.testServerPort(); int httpsPort = 0; final TestServer testServer = Helpers.testServer(port, httpsPort); diff --git a/testkit/play-test-junit5/src/test/resources/logback-test.xml b/testkit/play-test-junit5/src/test/resources/logback-test.xml new file mode 100644 index 00000000000..1f4fdac4cc1 --- /dev/null +++ b/testkit/play-test-junit5/src/test/resources/logback-test.xml @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + + + %level %logger{15} - %message%n%ex{short} + + + + + + + + diff --git a/testkit/play-test/src/main/java/play/test/TestBrowser.java b/testkit/play-test/src/main/java/play/test/TestBrowser.java index 681ce3795cc..9d1deb813c6 100644 --- a/testkit/play-test/src/main/java/play/test/TestBrowser.java +++ b/testkit/play-test/src/main/java/play/test/TestBrowser.java @@ -99,7 +99,7 @@ public WebDriver.Options manage() { } /** Quits and releases the {@link WebDriver} */ - void quit() { + public void quit() { if (getDriver() != null) { getDriver().quit(); } From 62d8e46ed8cc0e509169a260a62f4b096075de63 Mon Sep 17 00:00:00 2001 From: "H. Habighorst" Date: Fri, 14 Jul 2023 10:49:00 +0200 Subject: [PATCH 03/15] #11839: MiMa rules --- project/BuildSettings.scala | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/project/BuildSettings.scala b/project/BuildSettings.scala index 8836d09df3c..ce208b68636 100644 --- a/project/BuildSettings.scala +++ b/project/BuildSettings.scala @@ -445,6 +445,10 @@ object BuildSettings { ProblemFilters.exclude[IncompatibleResultTypeProblem]("play.db.jpa.DefaultJPAApi.em"), ProblemFilters.exclude[IncompatibleResultTypeProblem]("play.db.jpa.JPAApi.em"), ProblemFilters.exclude[ReversedMissingMethodProblem]("play.db.jpa.JPAApi.em"), + // Splitting play-test to play-test (scala) + play-test-junit4 + play-test-junit5 + ProblemFilters.exclude[MissingClassProblem]("play.test.WithApplication"), + ProblemFilters.exclude[MissingClassProblem]("play.test.WithBrowser"), + ProblemFilters.exclude[MissingClassProblem]("play.test.WithServer"), ), (Compile / unmanagedSourceDirectories) += { val suffix = CrossVersion.partialVersion(scalaVersion.value) match { From 85b912a42f18c1fa853829adb35ac750ce4030d8 Mon Sep 17 00:00:00 2001 From: "H. Habighorst" Date: Fri, 14 Jul 2023 14:24:28 +0200 Subject: [PATCH 04/15] #11839: Migration of documentation --- build.sbt | 2 + .../main/tests/JavaFunctionalTest.md | 61 ++++++++----- .../working/javaGuide/main/tests/JavaTest.md | 40 ++++----- .../tests/JavaTestingWebServiceClients.md | 8 +- .../main/tests/JavaTestingWithDatabases.md | 26 +++--- .../main/tests/JavaTestingWithGuice.md | 44 +++++----- .../junit4}/BrowserFunctionalTest.java | 0 .../junit4}/FunctionalTest.java | 2 +- .../junit4}/ServerFunctionalTest.java | 2 +- .../junit5}/ControllerTest.java | 16 ++-- .../{tests => test/junit5}/DatabaseTest.java | 23 ++--- .../junit5}/FakeApplicationTest.java | 15 ++-- .../{tests => test/junit5}/GitHubClient.java | 5 +- .../junit5}/GitHubClientTest.java | 39 +++++---- .../javaguide/test/junit5/InjectionTest.java | 49 +++++++++++ .../junit5}/JavaTestingWebServiceClients.java | 15 ++-- .../junit5}/JavaTestingWithDatabases.java | 62 +++++++------- .../{tests => test/junit5}/MessagesTest.java | 12 +-- .../{tests => test/junit5}/MockitoTest.java | 11 ++- .../{tests => test/junit5}/ModelTest.java | 20 ++--- .../{tests => test/junit5}/SimpleTest.java | 14 +-- .../junit5}/controllers/HomeController.java | 2 +- .../test/junit5}/guice/Component.java | 2 +- .../test/junit5}/guice/ComponentModule.java | 2 +- .../test/junit5}/guice/DefaultComponent.java | 2 +- .../JavaGuiceApplicationBuilderTest.java | 85 +++++++++---------- .../test/junit5}/guice/MockComponent.java | 2 +- .../guice/controllers/Application.java | 4 +- .../{tests => test/junit5}/index.scala.html | 0 .../code/javaguide/tests/HamcrestTest.java | 21 ----- .../code/javaguide/tests/InjectionTest.java | 53 ------------ 31 files changed, 316 insertions(+), 323 deletions(-) rename documentation/manual/working/javaGuide/main/tests/code/javaguide/{tests => test/junit4}/BrowserFunctionalTest.java (100%) rename documentation/manual/working/javaGuide/main/tests/code/javaguide/{tests => test/junit4}/FunctionalTest.java (98%) rename documentation/manual/working/javaGuide/main/tests/code/javaguide/{tests => test/junit4}/ServerFunctionalTest.java (97%) rename documentation/manual/working/javaGuide/main/tests/code/javaguide/{tests => test/junit5}/ControllerTest.java (75%) rename documentation/manual/working/javaGuide/main/tests/code/javaguide/{tests => test/junit5}/DatabaseTest.java (68%) rename documentation/manual/working/javaGuide/main/tests/code/javaguide/{tests => test/junit5}/FakeApplicationTest.java (81%) rename documentation/manual/working/javaGuide/main/tests/code/javaguide/{tests => test/junit5}/GitHubClient.java (93%) rename documentation/manual/working/javaGuide/main/tests/code/javaguide/{tests => test/junit5}/GitHubClientTest.java (61%) create mode 100644 documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/InjectionTest.java rename documentation/manual/working/javaGuide/main/tests/code/javaguide/{tests => test/junit5}/JavaTestingWebServiceClients.java (84%) rename documentation/manual/working/javaGuide/main/tests/code/javaguide/{tests => test/junit5}/JavaTestingWithDatabases.java (67%) rename documentation/manual/working/javaGuide/main/tests/code/javaguide/{tests => test/junit5}/MessagesTest.java (78%) rename documentation/manual/working/javaGuide/main/tests/code/javaguide/{tests => test/junit5}/MockitoTest.java (78%) rename documentation/manual/working/javaGuide/main/tests/code/javaguide/{tests => test/junit5}/ModelTest.java (86%) rename documentation/manual/working/javaGuide/main/tests/code/javaguide/{tests => test/junit5}/SimpleTest.java (56%) rename documentation/manual/working/javaGuide/main/tests/code/javaguide/{tests => test/junit5}/controllers/HomeController.java (90%) rename documentation/manual/working/javaGuide/main/tests/code/{tests => javaguide/test/junit5}/guice/Component.java (86%) rename documentation/manual/working/javaGuide/main/tests/code/{tests => javaguide/test/junit5}/guice/ComponentModule.java (91%) rename documentation/manual/working/javaGuide/main/tests/code/{tests => javaguide/test/junit5}/guice/DefaultComponent.java (89%) rename documentation/manual/working/javaGuide/main/tests/code/{tests => javaguide/test/junit5}/guice/JavaGuiceApplicationBuilderTest.java (74%) rename documentation/manual/working/javaGuide/main/tests/code/{tests => javaguide/test/junit5}/guice/MockComponent.java (88%) rename documentation/manual/working/javaGuide/main/tests/code/{tests => javaguide/test/junit5}/guice/controllers/Application.java (84%) rename documentation/manual/working/javaGuide/main/tests/code/javaguide/{tests => test/junit5}/index.scala.html (100%) delete mode 100644 documentation/manual/working/javaGuide/main/tests/code/javaguide/tests/HamcrestTest.java delete mode 100644 documentation/manual/working/javaGuide/main/tests/code/javaguide/tests/InjectionTest.java diff --git a/build.sbt b/build.sbt index cc3882aedb4..47470884966 100644 --- a/build.sbt +++ b/build.sbt @@ -499,6 +499,8 @@ lazy val userProjects = Seq[ProjectReference]( PlayOpenIdProject, PlaySpecs2Project, PlayTestProject, + PlayTestJUnit4Project, + PlayTestJUnit5Project, PlayExceptionsProject, PlayFiltersHelpersProject, StreamsProject, diff --git a/documentation/manual/working/javaGuide/main/tests/JavaFunctionalTest.md b/documentation/manual/working/javaGuide/main/tests/JavaFunctionalTest.md index 2cc095367fe..e423e7b790c 100644 --- a/documentation/manual/working/javaGuide/main/tests/JavaFunctionalTest.md +++ b/documentation/manual/working/javaGuide/main/tests/JavaFunctionalTest.md @@ -1,12 +1,23 @@ + + # Writing functional tests -Play provides a number of classes and convenience methods that assist with functional testing. Most of these can be found either in the [`play.test`](api/java/play/test/package-summary.html) package or in the [`Helpers`](api/java/play/test/Helpers.html) class. +Play provides a number of classes and convenience methods that assist with functional testing. + +For scala code, helpers can be found in the [`play.test`](api/java/play/test/package-summary.html) package or in the [`Helpers`](api/java/play/test/Helpers.html) class. + +Depending on framework, additional helpers are provided: + +- [JUnit 5](https://junit.org/junit5/): [`play.test.junit5`](api/play/test/junit5/package-summary.html) +- [JUnit 4](https://junit.org/junit4/): [`play.test.junit4`](api/play/test/junit4/package-summary.html) + +# [JUnit 5](https://junit.org/junit5/) test helpers You can add these methods and classes by importing the following: -@[test-imports](code/javaguide/tests/FakeApplicationTest.java) +@[test-imports](code/javaguide/test/junit5/FakeApplicationTest.java) ## Creating `Application` instances for testing @@ -16,43 +27,49 @@ Play frequently requires a running [`Application`](api/java/play/Application.htm import static play.test.Helpers.*; ``` -@[test-fakeapp](code/javaguide/tests/FakeApplicationTest.java) - -## Injecting tests - -If you're using Guice for [[dependency injection|JavaDependencyInjection]] then an `Application` for testing can be [[built directly|JavaTestingWithGuice]]. You can also inject any members of a test class that you might need. It's generally best practice to inject members only in functional tests and to manually create instances in unit tests. - -@[test-injection](code/javaguide/tests/InjectionTest.java) +@[test-fakeapp](code/javaguide/test/junit5/FakeApplicationTest.java) ## Testing with an application To run tests with an `Application`, you can do the following: -@[test-running-fakeapp](code/javaguide/tests/FakeApplicationTest.java) +@[test-running-fakeapp](code/javaguide/test/junit5/FakeApplicationTest.java) -You can also extend [`WithApplication`](api/java/play/test/WithApplication.html), this will automatically ensure that an application is started and stopped for each test method: +## Injecting tests -@[test-withapp](code/javaguide/tests/FunctionalTest.java) +If you're using Guice for [[dependency injection|JavaDependencyInjection]] then an `Application` for testing can be [[built directly|JavaTestingWithGuice]]. You can also inject any members of a test class that you might need. It's generally best practice to inject members only in functional tests and to manually create instances in unit tests. + +@[test-injection](code/javaguide/test/junit5/InjectionTest.java) ## Testing with a Guice application To run tests with an `Application` [[created by Guice|JavaTestingWithGuice]], you can do the following: -@[test-guiceapp](code/tests/guice/JavaGuiceApplicationBuilderTest.java) +@[test-guiceapp](code/javaguide/test/junit5/guice/JavaGuiceApplicationBuilderTest.java) Note that there are different ways to customize the `Application` creation when using Guice to test. +# [JUnit 4](https://junit.org/junit4/) Test Helpers + +## Testing with an application + +To run JUnit 4 tests with an application, one can extend [`WithApplication`](api/play/test/junit4/WithApplication.html). + +This will automatically ensure that an application is started and stopped for each test method: + +@[test-withapp](code/javaguide/test/junit4/FunctionalTest.java) + ## Testing a Controller Action through Routing With a running application, you can retrieve an action reference from the path for a route and invoke it. This also allows you to use `RequestBuilder` which creates a fake request: -@[bad-route-import](code/javaguide/tests/FunctionalTest.java) +@[bad-route-import](code/javaguide/test/junit4/FunctionalTest.java) -@[bad-route](code/javaguide/tests/FunctionalTest.java) +@[bad-route](code/javaguide/test/junit4/FunctionalTest.java) It is also possible to create the `RequestBuilder` using the reverse router directly and avoid hard-coding the router path: -@[good-route](code/javaguide/tests/FunctionalTest.java) +@[good-route](code/javaguide/test/junit4/FunctionalTest.java) > **Note:** the reverse router is not executing the action, but instead only providing a `Call` with information that will be used to create the `RequestBuilder` and later invoke the the action itself using `Helpers.route(Application, RequestBuilder)`. That is why it is not necessary to pass a `Http.Request` when using the reverse router to create the `Http.RequestBuilder` in tests even if the action is receiving a `Http.Request` as a parameter. @@ -60,18 +77,18 @@ It is also possible to create the `RequestBuilder` using the reverse router dire Sometimes you want to test the real HTTP stack from within your test. You can do this by starting a test server: -@[test-server](code/javaguide/tests/FunctionalTest.java) +@[test-server](code/javaguide/test/junit4/FunctionalTest.java) -Just as there exists a `WithApplication` class, there is also a [`WithServer`](api/java/play/test/WithServer.html) which you can extend to automatically start and stop a [`TestServer`](api/java/play/test/TestServer.html) for your tests: +Just as there exists a `WithApplication` class, there is also a [`WithServer`](api/play/test/junit4/WithBrowser.html) which you can extend to automatically start and stop a [`TestServer`](api/play/test/TestServer.html) for your tests: -@[test-withserver](code/javaguide/tests/ServerFunctionalTest.java) +@[test-withserver](code/javaguide/test/junit4/ServerFunctionalTest.java) ## Testing with a browser If you want to test your application from with a Web browser, you can use [Selenium WebDriver](https://github.com/seleniumhq/selenium). Play will start the WebDriver for you, and wrap it in the convenient API provided by [FluentLenium](https://github.com/FluentLenium/FluentLenium). -@[test-browser](code/javaguide/tests/FunctionalTest.java) +@[test-browser](code/javaguide/test/junit4/FunctionalTest.java) -And, of course there, is the [`WithBrowser`](api/java/play/test/WithBrowser.html) class to automatically open and close a browser for each test: +And, of course there, is the [`WithBrowser`](api/play/test/junit4/WithBrowser.html) class to automatically open and close a browser for each test: -@[test-withbrowser](code/javaguide/tests/BrowserFunctionalTest.java) +@[test-withbrowser](code/javaguide/test/junit4/BrowserFunctionalTest.java) diff --git a/documentation/manual/working/javaGuide/main/tests/JavaTest.md b/documentation/manual/working/javaGuide/main/tests/JavaTest.md index 5b5aceb7944..b445840935a 100644 --- a/documentation/manual/working/javaGuide/main/tests/JavaTest.md +++ b/documentation/manual/working/javaGuide/main/tests/JavaTest.md @@ -2,7 +2,9 @@ # Testing your application -Writing tests for your application can be an involved process. Play supports [JUnit](https://junit.org/junit5/) and provides helpers and application stubs to make testing your application as easy as possible. +Writing tests for your application can be an involved process. + +Play supports [JUnit 5](https://junit.org/junit5/) and [JUnit 4](https://junit.org/junit4/) and provides helpers and application stubs to make testing your application as easy as possible. ## Overview @@ -18,11 +20,13 @@ You can run tests from the sbt console. Testing in Play is based on [sbt](https://www.scala-sbt.org/), and a full description is available in the [testing documentation](https://www.scala-sbt.org/release/docs/Testing.html). -## Using JUnit +## Using JUnit 5 + +The default way to test a Play application is with [JUnit 5](https://junit.org/junit5/). -The default way to test a Play application is with [JUnit](https://junit.org/junit5/). +To run JUnit 5 tests, the following SBT plugin is necessary: [SBT Jupiter Interface](https://github.com/sbt/sbt-jupiter-interface). -@[test-simple](code/javaguide/tests/SimpleTest.java) +@[test-simple](code/javaguide/test/junit5/SimpleTest.java) > **Note:** A new process is forked each time `test` or `test-only` is run. The new process uses default JVM settings. Custom settings can be added to `build.sbt`. For example: @@ -35,14 +39,6 @@ The default way to test a Play application is with [JUnit](https://junit.org/jun > ) > ``` -### Assertions & Matchers - -Some developers prefer to write their assertions in a more fluent style than JUnit asserts. Popular libraries for other assertion styles are included for convenience. - -[Hamcrest](http://hamcrest.org/JavaHamcrest/) matchers: - -@[test-hamcrest](code/javaguide/tests/HamcrestTest.java) - ### Mocks Mocks are used to isolate unit tests against external dependencies. For example, if your class under test depends on an external data access class, you can mock this to provide controlled data and eliminate the need for an external data resource. @@ -50,51 +46,51 @@ Mocks are used to isolate unit tests against external dependencies. For example, The [Mockito](https://github.com/mockito/mockito) library is a popular mocking framework for Java. To use it in your tests add a dependency on the `mockito-core` artifact to your `build.sbt` file. For example: ```scala -libraryDependencies += "org.mockito" % "mockito-core" % "2.10.0" % "test" +libraryDependencies += "org.mockito" % "mockito-core" % "5.4.0" % Test ``` You can find the current version number of `mockito-core` [here](https://mvnrepository.com/artifact/org.mockito/mockito-core). Using Mockito, you can mock classes or interfaces like so: -@[test-mockito-import](code/javaguide/tests/MockitoTest.java) +@[test-mockito-import](code/javaguide/test/junit5/MockitoTest.java) -@[test-mockito](code/javaguide/tests/MockitoTest.java) +@[test-mockito](code/javaguide/test/junit5/MockitoTest.java) ## Unit testing models Let's assume we have the following data model: -@[test-model](code/javaguide/tests/ModelTest.java) +@[test-model](code/javaguide/test/junit5/ModelTest.java) Some data access libraries such as [Ebean](https://ebean.io/) allow you to put data access logic directly in your model classes using static methods. This can make mocking a data dependency tricky. A common approach for testability is to keep the models isolated from the database and as much logic as possible, and abstract database access behind a repository interface. -@[test-model-repository](code/javaguide/tests/ModelTest.java) +@[test-model-repository](code/javaguide/test/junit5/ModelTest.java) Then use a service that contains your repository to interact with your models: -@[test-model-service](code/javaguide/tests/ModelTest.java) +@[test-model-service](code/javaguide/test/junit5/ModelTest.java) In this way, the `UserService.isAdmin` method can be tested by mocking the `UserRepository` dependency: -@[test-model-test](code/javaguide/tests/ModelTest.java) +@[test-model-test](code/javaguide/test/junit5/ModelTest.java) ## Unit testing controllers You can test your controllers using Play's [test helpers](api/java/play/test/Helpers.html) to extract useful properties. -@[test-controller-test](code/javaguide/tests/ControllerTest.java) +@[test-controller-test](code/javaguide/test/junit5/ControllerTest.java) ## Unit testing view templates As a template is a just a method, you can execute it from a test and check the result: -@[test-template](code/javaguide/tests/ControllerTest.java) +@[test-template](code/javaguide/test/junit5/ControllerTest.java) ## Unit testing with Messages If you need a `play.i18n.MessagesApi` instance for unit testing, you can use [`play.test.Helpers.stubMessagesApi()`](api/java/play/test/Helpers.html#stubMessagesApi\(java.util.Map,play.i18n.Langs\)) to provide one: -@[test-messages](code/javaguide/tests/MessagesTest.java) +@[test-messages](code/javaguide/test/junit5/MessagesTest.java) diff --git a/documentation/manual/working/javaGuide/main/tests/JavaTestingWebServiceClients.md b/documentation/manual/working/javaGuide/main/tests/JavaTestingWebServiceClients.md index 57d31c55b93..e2c91fa2372 100644 --- a/documentation/manual/working/javaGuide/main/tests/JavaTestingWebServiceClients.md +++ b/documentation/manual/working/javaGuide/main/tests/JavaTestingWebServiceClients.md @@ -26,19 +26,19 @@ Play provides some helper utilities for mocking a web service in tests, making t As an example, let's say you've written a GitHub client, and you want to test it. The client is very simple, it just allows you to look up the names of the public repositories: -@[client](code/javaguide/tests/GitHubClient.java) +@[client](code/javaguide/test/junit5/GitHubClient.java) Note that it takes the GitHub API base URL as a parameter - we'll override this in our tests so that we can point it to our mock server. To test this, we want an embedded Play server that will implement this endpoint. We can do that by [[Creating an embedded server|JavaEmbeddingPlay]] with the [[Routing DSL|JavaRoutingDsl]]: -@[mock-service](code/javaguide/tests/JavaTestingWebServiceClients.java) +@[mock-service](code/javaguide/test/junit5/JavaTestingWebServiceClients.java) Our server is now running on a random port, that we can access through the `httpPort` method. We could build the base URL to pass to the `GitHubClient` using this, however Play has an even simpler mechanism. The [`WSTestClient`](api/java/play/test/WSTestClient.html) class provides a `newClient` method that takes in a port number. When requests are made using the client to relative URLs, eg to `/repositories`, this client will send that request to localhost on the passed in port. This means we can set a base URL on the `GitHubClient` to `""`. It also means if the client returns resources with URL links to other resources that the client then uses to make further requests, we can just ensure those a relative URLs and use them as is. So now we can create a server, WS client and `GitHubClient` in a `@Before` annotated method, and shut them down in an `@After` annotated method, and then we can test the client in our tests: -@[content](code/javaguide/tests/GitHubClientTest.java) +@[content](code/javaguide/test/junit5/GitHubClientTest.java) ### Returning files @@ -84,6 +84,6 @@ You may decide to modify it to suit your testing needs, for example, if your Git Now, modify the router to serve this resource: -@[send-resource](code/javaguide/tests/JavaTestingWebServiceClients.java) +@[send-resource](code/javaguide/test/junit5/JavaTestingWebServiceClients.java) Note that Play will automatically set a content type of `application/json` due to the filename's extension of `.json`. diff --git a/documentation/manual/working/javaGuide/main/tests/JavaTestingWithDatabases.md b/documentation/manual/working/javaGuide/main/tests/JavaTestingWithDatabases.md index 23d28870c92..239d00aa65a 100644 --- a/documentation/manual/working/javaGuide/main/tests/JavaTestingWithDatabases.md +++ b/documentation/manual/working/javaGuide/main/tests/JavaTestingWithDatabases.md @@ -14,21 +14,21 @@ To test with a database backend, you only need: To connect to a database, at a minimum, you just need database driver name and the url of the database, using the [`Database`](api/java/play/db/Database.html) static factory methods. For example, to connect to MySQL, you might use the following: -@[database](code/javaguide/tests/JavaTestingWithDatabases.java) +@[database](code/javaguide/test/junit5/JavaTestingWithDatabases.java) This will create a database connection pool for the MySQL `test` database running on `localhost`, with the name `default`. The name of the database is only used internally by Play, for example, by other features such as evolutions, to load resources associated with that database. You may want to specify other configuration for the database, including a custom name, or configuration properties such as usernames, passwords and the various connection pool configuration items that Play supports, by supplying a custom name parameter and/or a custom config parameter: -@[full-config](code/javaguide/tests/JavaTestingWithDatabases.java) +@[full-config](code/javaguide/test/junit5/JavaTestingWithDatabases.java) After using a database, since the database is typically backed by a connection pool that holds open connections and may also have running threads, you need to shut it down. This is done by calling the `shutdown` method: -@[shutdown](code/javaguide/tests/JavaTestingWithDatabases.java) +@[shutdown](code/javaguide/test/junit5/JavaTestingWithDatabases.java) These methods are particularly useful if you use them in combination with JUnit's `@Before` and `@After` annotations, for example: -@[database-junit](code/javaguide/tests/JavaTestingWithDatabases.java) +@[database-junit](code/javaguide/test/junit5/JavaTestingWithDatabases.java) > **Tip:** You can use this to externalize your test database configuration, using environment variables or system properties to configure what database to use and how to connect to it. This allows for maximum flexibility for developers to have their own environments set up the way they please, as well as for CI systems that provide particular environments that may differ to development. @@ -36,15 +36,15 @@ These methods are particularly useful if you use them in combination with JUnit' Some people prefer not to require infrastructure such as databases to be installed in order to run tests. Play provides simple helpers to create an H2 in-memory database for these purposes: -@[in-memory](code/javaguide/tests/JavaTestingWithDatabases.java) +@[in-memory](code/javaguide/test/junit5/JavaTestingWithDatabases.java) The in-memory database can be configured by supplying a custom name, custom URL arguments, and custom connection pool configuration. The following shows supplying the `MODE` argument to tell H2 to emulate `MySQL`, as well as configuring the connection pool to log all statements: -@[in-memory-full-config](code/javaguide/tests/JavaTestingWithDatabases.java) +@[in-memory-full-config](code/javaguide/test/junit5/JavaTestingWithDatabases.java) As with the generic database factory, ensure you always shut the in-memory database connection pool down: -@[in-memory-shutdown](code/javaguide/tests/JavaTestingWithDatabases.java) +@[in-memory-shutdown](code/javaguide/test/junit5/JavaTestingWithDatabases.java) ## Applying evolutions @@ -52,29 +52,29 @@ When running tests, you will typically want your database schema managed for you To apply evolutions, you can use `applyEvolutions` from the [`Evolutions`](api/java/play/db/evolutions/Evolutions.html) static class: -@[apply-evolutions](code/javaguide/tests/JavaTestingWithDatabases.java) +@[apply-evolutions](code/javaguide/test/junit5/JavaTestingWithDatabases.java) This will load the evolutions from the classpath in the `evolutions/` directory, and apply them. After a test has run, you may want to reset the database to its original state. If you have implemented your evolutions down scripts in such a way that they will drop all the database tables, you can do this simply by calling the `cleanupEvolutions` method: -@[cleanup-evolutions](code/javaguide/tests/JavaTestingWithDatabases.java) +@[cleanup-evolutions](code/javaguide/test/junit5/JavaTestingWithDatabases.java) ### Custom evolutions In some situations you may want to run some custom evolutions in your tests. Custom evolutions can be used by using a custom [`EvolutionsReader`](api/java/play/db/evolutions/EvolutionsReader.html). The easiest way to do this is using the static factory methods on `Evolutions`, for example `forDefault` creates an evolutions reader for a simple list of [`Evolution`](api/java/play/db/evolutions/Evolution.html) scripts for the default database. For example: -@[apply-evolutions-simple](code/javaguide/tests/JavaTestingWithDatabases.java) +@[apply-evolutions-simple](code/javaguide/test/junit5/JavaTestingWithDatabases.java) Cleaning up custom evolutions is done in the same way as cleaning up regular evolutions, using the `cleanupEvolutions` method: -@[cleanup-evolutions-simple](code/javaguide/tests/JavaTestingWithDatabases.java) +@[cleanup-evolutions-simple](code/javaguide/test/junit5/JavaTestingWithDatabases.java) Note though that you don't need to pass the custom evolutions reader here, this is because the state of the evolutions is stored in the database, including the down scripts which will be used to tear down the database. Sometimes it will be impractical to put your custom evolution scripts in code. If this is the case, you can put them in the test resources directory, using the `fromClassLoader` factory method: -@[apply-evolutions-custom-path](code/javaguide/tests/JavaTestingWithDatabases.java) +@[apply-evolutions-custom-path](code/javaguide/test/junit5/JavaTestingWithDatabases.java) This will load evolutions, in the same structure and format as is done for development and production, from `testdatabase/evolutions//.sql`. @@ -82,4 +82,4 @@ This will load evolutions, in the same structure and format as is done for devel Typically you will have many tests that you want to run with the same evolutions, so it will make sense to extract the evolutions setup code into before and after methods, along with the database setup and tear down code. Here is what a complete test might look like: -@[database-test](code/javaguide/tests/DatabaseTest.java) +@[database-test](code/javaguide/test/junit5/DatabaseTest.java) diff --git a/documentation/manual/working/javaGuide/main/tests/JavaTestingWithGuice.md b/documentation/manual/working/javaGuide/main/tests/JavaTestingWithGuice.md index f604efbdf4f..6a050a0269c 100644 --- a/documentation/manual/working/javaGuide/main/tests/JavaTestingWithGuice.md +++ b/documentation/manual/working/javaGuide/main/tests/JavaTestingWithGuice.md @@ -12,24 +12,24 @@ If you're using Guice for [[dependency injection|JavaDependencyInjection]] then The main imports you'll need for building applications with Guice are: -@[builder-imports](code/tests/guice/JavaGuiceApplicationBuilderTest.java) +@[builder-imports](code/javaguide/test/junit5/guice/JavaGuiceApplicationBuilderTest.java) ### Environment The [Environment](api/java/play/Environment.html), or parts of the environment such as the root path, mode, or class loader for an application, can be specified. The configured environment will be used for loading the application configuration, it will be used when loading modules and passed when deriving bindings from Play modules, and it will be injectable into other components. -@[set-environment](code/tests/guice/JavaGuiceApplicationBuilderTest.java) -@[set-environment-values](code/tests/guice/JavaGuiceApplicationBuilderTest.java) +@[set-environment](code/javaguide/test/junit5/guice/JavaGuiceApplicationBuilderTest.java) +@[set-environment-values](code/javaguide/test/junit5/guice/JavaGuiceApplicationBuilderTest.java) ### Configuration Additional configuration can be added. This configuration will always be in addition to the configuration loaded automatically for the application. When existing keys are used the new configuration will be preferred. -@[add-configuration](code/tests/guice/JavaGuiceApplicationBuilderTest.java) +@[add-configuration](code/javaguide/test/junit5/guice/JavaGuiceApplicationBuilderTest.java) The automatic loading of configuration from the application environment can also be overridden. This will completely replace the application configuration. For example: -@[override-configuration](code/tests/guice/JavaGuiceApplicationBuilderTest.java) +@[override-configuration](code/javaguide/test/junit5/guice/JavaGuiceApplicationBuilderTest.java) ### Bindings and Modules @@ -39,60 +39,60 @@ The bindings used for dependency injection are completely configurable. The buil Additional bindings, via Play modules, Play bindings, or Guice modules, can be added: -@[bind-imports](code/tests/guice/JavaGuiceApplicationBuilderTest.java) -@[add-bindings](code/tests/guice/JavaGuiceApplicationBuilderTest.java) +@[bind-imports](code/javaguide/test/junit5/guice/JavaGuiceApplicationBuilderTest.java) +@[add-bindings](code/javaguide/test/junit5/guice/JavaGuiceApplicationBuilderTest.java) #### Override bindings Bindings can be overridden using Play bindings, or modules that provide bindings. For example: -@[override-bindings](code/tests/guice/JavaGuiceApplicationBuilderTest.java) +@[override-bindings](code/javaguide/test/junit5/guice/JavaGuiceApplicationBuilderTest.java) #### Disable modules Any loaded modules can be disabled by class name: -@[disable-modules](code/tests/guice/JavaGuiceApplicationBuilderTest.java) +@[disable-modules](code/javaguide/test/junit5/guice/JavaGuiceApplicationBuilderTest.java) #### Loaded modules Modules are automatically loaded from the classpath based on the `play.modules.enabled` configuration. This default loading of modules can be overridden. For example: -@[guiceable-imports](code/tests/guice/JavaGuiceApplicationBuilderTest.java) -@[load-modules](code/tests/guice/JavaGuiceApplicationBuilderTest.java) +@[guiceable-imports](code/javaguide/test/junit5/guice/JavaGuiceApplicationBuilderTest.java) +@[load-modules](code/javaguide/test/junit5/guice/JavaGuiceApplicationBuilderTest.java) ## GuiceInjectorBuilder [GuiceInjectorBuilder](api/java/play/inject/guice/GuiceInjectorBuilder.html) provides a builder API for configuring Guice dependency injection more generally. This builder does not load configuration or modules automatically from the environment like `GuiceApplicationBuilder`, but provides a completely clean state for adding configuration and bindings. The common interface for both builders can be found in [GuiceBuilder](api/java/play/inject/guice/GuiceBuilder.html). A Play [Injector](api/java/play/inject/Injector.html) is created. Here's an example of instantiating a component using the injector builder: -@[injector-imports](code/tests/guice/JavaGuiceApplicationBuilderTest.java) -@[bind-imports](code/tests/guice/JavaGuiceApplicationBuilderTest.java) -@[injector-builder](code/tests/guice/JavaGuiceApplicationBuilderTest.java) +@[injector-imports](code/javaguide/test/junit5/guice/JavaGuiceApplicationBuilderTest.java) +@[bind-imports](code/javaguide/test/junit5/guice/JavaGuiceApplicationBuilderTest.java) +@[injector-builder](code/javaguide/test/junit5/guice/JavaGuiceApplicationBuilderTest.java) ## Overriding bindings in a functional test Here is a full example of replacing a component with a mock component for testing. Let's start with a component, that has a default implementation and a mock implementation for testing: -@[component](code/tests/guice/Component.java) +@[component](code/javaguide/test/junit5/guice/Component.java) -@[default-component](code/tests/guice/DefaultComponent.java) +@[default-component](code/javaguide/test/junit5/guice/DefaultComponent.java) -@[mock-component](code/tests/guice/MockComponent.java) +@[mock-component](code/javaguide/test/junit5/guice/MockComponent.java) This component is loaded automatically using a module: -@[component-module](code/tests/guice/ComponentModule.java) +@[component-module](code/javaguide/test/junit5/guice/ComponentModule.java) And the component is used in a controller: -@[controller](code/tests/guice/controllers/Application.java) +@[controller](code/javaguide/test/junit5/guice/controllers/Application.java) To build an `Application` to use in [[functional tests|JavaFunctionalTest]] we can simply override the binding for the component: -@[builder-imports](code/tests/guice/JavaGuiceApplicationBuilderTest.java) -@[bind-imports](code/tests/guice/JavaGuiceApplicationBuilderTest.java) -@[override-bindings](code/tests/guice/JavaGuiceApplicationBuilderTest.java) +@[builder-imports](code/javaguide/test/junit5/guice/JavaGuiceApplicationBuilderTest.java) +@[bind-imports](code/javaguide/test/junit5/guice/JavaGuiceApplicationBuilderTest.java) +@[override-bindings](code/javaguide/test/junit5/guice/JavaGuiceApplicationBuilderTest.java) This application can be used with test helpers such as `running` and `WithApplication`. diff --git a/documentation/manual/working/javaGuide/main/tests/code/javaguide/tests/BrowserFunctionalTest.java b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit4/BrowserFunctionalTest.java similarity index 100% rename from documentation/manual/working/javaGuide/main/tests/code/javaguide/tests/BrowserFunctionalTest.java rename to documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit4/BrowserFunctionalTest.java diff --git a/documentation/manual/working/javaGuide/main/tests/code/javaguide/tests/FunctionalTest.java b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit4/FunctionalTest.java similarity index 98% rename from documentation/manual/working/javaGuide/main/tests/code/javaguide/tests/FunctionalTest.java rename to documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit4/FunctionalTest.java index e658b294461..67de9a73eef 100644 --- a/documentation/manual/working/javaGuide/main/tests/code/javaguide/tests/FunctionalTest.java +++ b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit4/FunctionalTest.java @@ -2,7 +2,7 @@ * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. */ -package javaguide.tests; +package javaguide.test.junit4; import java.util.HashMap; import java.util.Map; diff --git a/documentation/manual/working/javaGuide/main/tests/code/javaguide/tests/ServerFunctionalTest.java b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit4/ServerFunctionalTest.java similarity index 97% rename from documentation/manual/working/javaGuide/main/tests/code/javaguide/tests/ServerFunctionalTest.java rename to documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit4/ServerFunctionalTest.java index b5fceafc554..b88e9ebe00d 100644 --- a/documentation/manual/working/javaGuide/main/tests/code/javaguide/tests/ServerFunctionalTest.java +++ b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit4/ServerFunctionalTest.java @@ -2,7 +2,7 @@ * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. */ -package javaguide.tests; +package javaguide.test.junit4; import static org.junit.Assert.*; import static play.test.Helpers.NOT_FOUND; diff --git a/documentation/manual/working/javaGuide/main/tests/code/javaguide/tests/ControllerTest.java b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/ControllerTest.java similarity index 75% rename from documentation/manual/working/javaGuide/main/tests/code/javaguide/tests/ControllerTest.java rename to documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/ControllerTest.java index 04955196d7f..981aac023cf 100644 --- a/documentation/manual/working/javaGuide/main/tests/code/javaguide/tests/ControllerTest.java +++ b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/ControllerTest.java @@ -2,23 +2,23 @@ * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. */ -package javaguide.tests; +package javaguide.test.junit5; // #test-controller-test -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import static play.mvc.Http.Status.OK; import static play.test.Helpers.*; -import javaguide.tests.controllers.HomeController; -import org.junit.Test; +import javaguide.test.junit5.controllers.HomeController; +import org.junit.jupiter.api.Test; import play.mvc.Result; import play.twirl.api.Content; -public class ControllerTest { +class ControllerTest { @Test - public void testIndex() { + void testIndex() { Result result = new HomeController().index(); assertEquals(OK, result.status()); assertEquals("text/html", result.contentType().get()); @@ -31,7 +31,7 @@ public void testIndex() { // #test-template @Test - public void renderTemplate() { + void renderTemplate() { // ###replace: Content html = views.html.index.render("Welcome to Play!"); Content html = javaguide.tests.html.index.render("Welcome to Play!"); assertEquals("text/html", html.contentType()); diff --git a/documentation/manual/working/javaGuide/main/tests/code/javaguide/tests/DatabaseTest.java b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/DatabaseTest.java similarity index 68% rename from documentation/manual/working/javaGuide/main/tests/code/javaguide/tests/DatabaseTest.java rename to documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/DatabaseTest.java index ecb541ae7c4..fa3460c55b3 100644 --- a/documentation/manual/working/javaGuide/main/tests/code/javaguide/tests/DatabaseTest.java +++ b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/DatabaseTest.java @@ -2,23 +2,26 @@ * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. */ -package javaguide.tests; +package javaguide.test.junit5; // #database-test -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.sql.Connection; -import org.junit.*; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import play.db.Database; import play.db.Databases; -import play.db.evolutions.*; +import play.db.evolutions.Evolution; +import play.db.evolutions.Evolutions; -public class DatabaseTest { +class DatabaseTest { Database database; - @Before - public void setupDatabase() { + @BeforeAll + static void setupDatabase() { database = Databases.inMemory(); Evolutions.applyEvolutions( database, @@ -29,14 +32,14 @@ public void setupDatabase() { "drop table test;"))); } - @After - public void shutdownDatabase() { + @AfterAll + static void shutdownDatabase() { Evolutions.cleanupEvolutions(database); database.shutdown(); } @Test - public void testDatabase() throws Exception { + void testDatabase() throws Exception { Connection connection = database.getConnection(); connection.prepareStatement("insert into test values (10, 'testing')").execute(); diff --git a/documentation/manual/working/javaGuide/main/tests/code/javaguide/tests/FakeApplicationTest.java b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/FakeApplicationTest.java similarity index 81% rename from documentation/manual/working/javaGuide/main/tests/code/javaguide/tests/FakeApplicationTest.java rename to documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/FakeApplicationTest.java index f24eea05efd..1d2c64ffb96 100644 --- a/documentation/manual/working/javaGuide/main/tests/code/javaguide/tests/FakeApplicationTest.java +++ b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/FakeApplicationTest.java @@ -2,19 +2,18 @@ * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. */ -package javaguide.tests; +package javaguide.test.junit5; + +import static org.junit.jupiter.api.Assertions.assertEquals; // #test-imports -import play.test.*; import static play.test.Helpers.*; // #test-imports -import org.junit.Test; -import static org.junit.Assert.*; - +import org.junit.jupiter.api.Test; import play.Application; -public class FakeApplicationTest { +class FakeApplicationTest { public static class Computer { public String name = "Macintosh"; @@ -31,11 +30,11 @@ String formatted(String s) { // #test-running-fakeapp @Test - public void findById() { + void findById() { running( fakeApplication(inMemoryDatabase("test")), () -> { - Computer macintosh = Computer.findById(21l); + Computer macintosh = Computer.findById(21L); assertEquals("Macintosh", macintosh.name); assertEquals("1984-01-24", formatted(macintosh.introduced)); }); diff --git a/documentation/manual/working/javaGuide/main/tests/code/javaguide/tests/GitHubClient.java b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/GitHubClient.java similarity index 93% rename from documentation/manual/working/javaGuide/main/tests/code/javaguide/tests/GitHubClient.java rename to documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/GitHubClient.java index 0e707140c80..1921f856d72 100644 --- a/documentation/manual/working/javaGuide/main/tests/code/javaguide/tests/GitHubClient.java +++ b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/GitHubClient.java @@ -2,11 +2,12 @@ * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. */ -package javaguide.tests; +package javaguide.test.junit5; // #client + import com.fasterxml.jackson.databind.JsonNode; -import java.util.*; +import java.util.List; import java.util.concurrent.CompletionStage; import java.util.stream.Collectors; import javax.inject.Inject; diff --git a/documentation/manual/working/javaGuide/main/tests/code/javaguide/tests/GitHubClientTest.java b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/GitHubClientTest.java similarity index 61% rename from documentation/manual/working/javaGuide/main/tests/code/javaguide/tests/GitHubClientTest.java rename to documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/GitHubClientTest.java index 7ceaf1a2b82..0dd004dd749 100644 --- a/documentation/manual/working/javaGuide/main/tests/code/javaguide/tests/GitHubClientTest.java +++ b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/GitHubClientTest.java @@ -2,30 +2,33 @@ * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. */ -package javaguide.tests; +package javaguide.test.junit5; // #content -import static org.hamcrest.core.IsCollectionContaining.*; -import static org.junit.Assert.*; -import static play.mvc.Results.*; -import com.fasterxml.jackson.databind.node.*; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static play.mvc.Results.ok; + +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; import java.io.IOException; -import java.util.*; +import java.util.List; import java.util.concurrent.TimeUnit; -import org.junit.*; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import play.libs.Json; -import play.libs.ws.*; +import play.libs.ws.WSClient; import play.routing.RoutingDsl; import play.server.Server; -public class GitHubClientTest { - private GitHubClient client; - private WSClient ws; - private Server server; +class GitHubClientTest { + private static GitHubClient client; + private static WSClient ws; + private static Server server; - @Before - public void setup() { + @BeforeAll + static void setup() { server = Server.forRouter( (components) -> @@ -45,8 +48,8 @@ public void setup() { client.baseUrl = ""; } - @After - public void tearDown() throws IOException { + @AfterAll + static void tearDown() throws IOException { try { ws.close(); } finally { @@ -55,9 +58,9 @@ public void tearDown() throws IOException { } @Test - public void repositories() throws Exception { + void repositories() throws Exception { List repos = client.getRepositories().toCompletableFuture().get(10, TimeUnit.SECONDS); - assertThat(repos, hasItem("octocat/Hello-World")); + assertTrue(repos.stream().anyMatch(item -> item.equals("octocat/Hello-World"))); } } // #content diff --git a/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/InjectionTest.java b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/InjectionTest.java new file mode 100644 index 00000000000..f659b0b8d44 --- /dev/null +++ b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/InjectionTest.java @@ -0,0 +1,49 @@ +/* + * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. + */ + +package javaguide.test.junit5; + +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import com.google.inject.AbstractModule; +import com.google.inject.Guice; +import com.google.inject.Module; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import play.Application; +import play.ApplicationLoader.Context; +import play.Environment; +import play.inject.guice.GuiceApplicationBuilder; +import play.inject.guice.GuiceApplicationLoader; +import play.test.junit5.ApplicationExtension; + +class InjectionTest { + + static Module testModule = + new AbstractModule() { + @Override + public void configure() { + // Install custom test binding here + } + }; + + // #test-injection + @RegisterExtension + static ApplicationExtension applicationExtension = new ApplicationExtension(createApplication()); + + static Application createApplication() { + GuiceApplicationBuilder builder = + new GuiceApplicationLoader() + .builder(new Context(Environment.simple())) + .overrides(testModule); + + return Guice.createInjector(builder.applicationModule()).getInstance(Application.class); + } + + @Test + void testApplication() { + Application application = applicationExtension.getApplication(); + assertNotNull(application); + } +} diff --git a/documentation/manual/working/javaGuide/main/tests/code/javaguide/tests/JavaTestingWebServiceClients.java b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/JavaTestingWebServiceClients.java similarity index 84% rename from documentation/manual/working/javaGuide/main/tests/code/javaguide/tests/JavaTestingWebServiceClients.java rename to documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/JavaTestingWebServiceClients.java index b2705dbeece..4bb66aae979 100644 --- a/documentation/manual/working/javaGuide/main/tests/code/javaguide/tests/JavaTestingWebServiceClients.java +++ b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/JavaTestingWebServiceClients.java @@ -2,25 +2,24 @@ * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. */ -package javaguide.tests; +package javaguide.test.junit5; -import static org.hamcrest.core.IsCollectionContaining.*; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import static play.mvc.Controller.*; import com.fasterxml.jackson.databind.node.*; import java.util.List; import java.util.concurrent.TimeUnit; -import org.junit.Test; +import org.junit.jupiter.api.Test; import play.libs.Json; import play.libs.ws.WSClient; import play.routing.RoutingDsl; import play.server.Server; -public class JavaTestingWebServiceClients { +class JavaTestingWebServiceClients { @Test - public void mockService() { + void mockService() { // #mock-service Server server = Server.forRouter( @@ -42,7 +41,7 @@ public void mockService() { } @Test - public void sendResource() throws Exception { + void sendResource() throws Exception { // #send-resource Server server = Server.forRouter( @@ -59,7 +58,7 @@ public void sendResource() throws Exception { try { List repos = client.getRepositories().toCompletableFuture().get(10, TimeUnit.SECONDS); - assertThat(repos, hasItem("octocat/Hello-World")); + assertTrue(repos.stream().anyMatch(item -> item.equals("octocat/Hello-World"))); } finally { try { ws.close(); diff --git a/documentation/manual/working/javaGuide/main/tests/code/javaguide/tests/JavaTestingWithDatabases.java b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/JavaTestingWithDatabases.java similarity index 67% rename from documentation/manual/working/javaGuide/main/tests/code/javaguide/tests/JavaTestingWithDatabases.java rename to documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/JavaTestingWithDatabases.java index 5c9431af016..450253446ce 100644 --- a/documentation/manual/working/javaGuide/main/tests/code/javaguide/tests/JavaTestingWithDatabases.java +++ b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/JavaTestingWithDatabases.java @@ -2,22 +2,25 @@ * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. */ -package javaguide.tests; +package javaguide.test.junit5; -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import com.google.common.collect.ImmutableMap; import java.sql.Connection; import java.sql.SQLException; -import org.junit.*; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import play.db.Database; import play.db.Databases; -import play.db.evolutions.*; +import play.db.evolutions.Evolution; +import play.db.evolutions.Evolutions; -public class JavaTestingWithDatabases { +class JavaTestingWithDatabases { - public static class NotTested { + static class NotTested { { // #database Database database = @@ -43,17 +46,17 @@ public static class NotTested { } - public static class ExampleUnitTest { + static class ExampleUnitTest { // #database-junit Database database; - @Before - public void createDatabase() { + @BeforeAll + static void createDatabase() { database = Databases.createFrom("com.mysql.jdbc.Driver", "jdbc:mysql://localhost/test"); } - @After - public void shutdownDatabase() { + @AfterAll + static void shutdownDatabase() { database.shutdown(); } // #database-junit @@ -61,20 +64,20 @@ public void shutdownDatabase() { } @Test - public void inMemory() throws Exception { + void inMemory() throws Exception { // #in-memory Database database = Databases.inMemory(); // #in-memory try { - assertThat(database.getConnection().getMetaData().getDatabaseProductName(), equalTo("H2")); + assertEquals("H2", database.getConnection().getMetaData().getDatabaseProductName()); } finally { database.shutdown(); } } @Test - public void inMemoryFullConfig() throws Exception { + void inMemoryFullConfig() throws Exception { // #in-memory-full-config Database database = Databases.inMemory( @@ -82,7 +85,7 @@ public void inMemoryFullConfig() throws Exception { // #in-memory-full-config try { - assertThat(database.getConnection().getMetaData().getDatabaseProductName(), equalTo("H2")); + assertEquals("H2", database.getConnection().getMetaData().getDatabaseProductName()); } finally { // #in-memory-shutdown database.shutdown(); @@ -91,7 +94,7 @@ public void inMemoryFullConfig() throws Exception { } @Test - public void evolutions() throws Exception { + void evolutions() throws Exception { Database database = Databases.inMemory(); try { // #apply-evolutions @@ -107,17 +110,15 @@ public void evolutions() throws Exception { } @Test - public void staticEvolutions() throws Exception { + void staticEvolutions() throws Exception { Database database = Databases.inMemory(); try { // #apply-evolutions-simple - Evolutions.applyEvolutions( - database, - Evolutions.forDefault( - new Evolution( - 1, - "create table test (id bigint not null, name varchar(255));", - "drop table test;"))); + final Evolution evolution = + new Evolution( + 1, "create table test (id bigint not null, name varchar(255));", "drop table test;"); + + Evolutions.applyEvolutions(database, Evolutions.forDefault(evolution)); // #apply-evolutions-simple Connection connection = database.getConnection(); @@ -127,19 +128,16 @@ public void staticEvolutions() throws Exception { Evolutions.cleanupEvolutions(database); // #cleanup-evolutions-simple - try { - connection.prepareStatement("select * from test").executeQuery(); - fail(); - } catch (SQLException e) { - // pass - } + assertThrows( + SQLException.class, + () -> connection.prepareStatement("select * from test").executeQuery()); } finally { database.shutdown(); } } @Test - public void customPathEvolutions() throws Exception { + void customPathEvolutions() throws Exception { Database database = Databases.inMemory(); try { // #apply-evolutions-custom-path diff --git a/documentation/manual/working/javaGuide/main/tests/code/javaguide/tests/MessagesTest.java b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/MessagesTest.java similarity index 78% rename from documentation/manual/working/javaGuide/main/tests/code/javaguide/tests/MessagesTest.java rename to documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/MessagesTest.java index 9455a05d874..28f8a40e847 100644 --- a/documentation/manual/working/javaGuide/main/tests/code/javaguide/tests/MessagesTest.java +++ b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/MessagesTest.java @@ -2,23 +2,23 @@ * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. */ -package javaguide.tests; +package javaguide.test.junit5; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Collections; import java.util.Map; -import org.junit.Test; +import org.junit.jupiter.api.Test; import play.i18n.Lang; import play.i18n.Langs; import play.i18n.Messages; import play.i18n.MessagesApi; -public class MessagesTest { +class MessagesTest { // #test-messages @Test - public void renderMessages() { + void renderMessages() { Langs langs = new Langs(new play.api.i18n.DefaultLangs()); Map messagesMap = Collections.singletonMap("foo", "bar"); @@ -27,7 +27,7 @@ public void renderMessages() { MessagesApi messagesApi = play.test.Helpers.stubMessagesApi(langMap, langs); Messages messages = messagesApi.preferred(langs.availables()); - assertEquals(messages.at("foo"), "bar"); + assertEquals("bar", messages.at("foo")); } // #test-messages diff --git a/documentation/manual/working/javaGuide/main/tests/code/javaguide/tests/MockitoTest.java b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/MockitoTest.java similarity index 78% rename from documentation/manual/working/javaGuide/main/tests/code/javaguide/tests/MockitoTest.java rename to documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/MockitoTest.java index 491e6794386..56bea355c4c 100644 --- a/documentation/manual/working/javaGuide/main/tests/code/javaguide/tests/MockitoTest.java +++ b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/MockitoTest.java @@ -2,23 +2,22 @@ * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. */ -package javaguide.tests; +package javaguide.test.junit5; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.assertEquals; // #test-mockito-import import static org.mockito.Mockito.*; // #test-mockito-import import java.util.List; +import org.junit.jupiter.api.Test; -import org.junit.Test; - -public class MockitoTest { +class MockitoTest { @Test @SuppressWarnings("unchecked") - public void testMockList() { + void testMockList() { // #test-mockito // Create and train mock diff --git a/documentation/manual/working/javaGuide/main/tests/code/javaguide/tests/ModelTest.java b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/ModelTest.java similarity index 86% rename from documentation/manual/working/javaGuide/main/tests/code/javaguide/tests/ModelTest.java rename to documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/ModelTest.java index 65d55c5de9f..4f6de846d77 100644 --- a/documentation/manual/working/javaGuide/main/tests/code/javaguide/tests/ModelTest.java +++ b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/ModelTest.java @@ -2,9 +2,9 @@ * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. */ -package javaguide.tests; +package javaguide.test.junit5; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -12,12 +12,12 @@ import java.util.HashSet; import java.util.Set; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class ModelTest { +class ModelTest { // #test-model - public class User { + class User { private Integer id; private String name; @@ -27,7 +27,7 @@ public User(final Integer id, final String name) { } } - public class Role { + class Role { private String name; public Role(final String name) { @@ -37,11 +37,11 @@ public Role(final String name) { // #test-model // #test-model-repository - public interface UserRepository { + interface UserRepository { public Set findUserRoles(User user); } - public class UserRepositoryEbean implements UserRepository { + class UserRepositoryEbean implements UserRepository { @Override public Set findUserRoles(User user) { // Get roles from DB @@ -52,7 +52,7 @@ public Set findUserRoles(User user) { // #test-model-repository // #test-model-service - public class UserService { + class UserService { private final UserRepository userRepository; public UserService(final UserRepository userRepository) { @@ -71,7 +71,7 @@ public boolean isAdmin(final User user) { // #test-model-test @Test - public void testIsAdmin() { + void testIsAdmin() { // Create and train mock repository UserRepository repositoryMock = mock(UserRepository.class); diff --git a/documentation/manual/working/javaGuide/main/tests/code/javaguide/tests/SimpleTest.java b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/SimpleTest.java similarity index 56% rename from documentation/manual/working/javaGuide/main/tests/code/javaguide/tests/SimpleTest.java rename to documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/SimpleTest.java index 031eaa93978..d26ba761e8c 100644 --- a/documentation/manual/working/javaGuide/main/tests/code/javaguide/tests/SimpleTest.java +++ b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/SimpleTest.java @@ -2,23 +2,25 @@ * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. */ -package javaguide.tests; +package javaguide.test.junit5; // #test-simple -import static org.junit.Assert.*; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; -public class SimpleTest { +import org.junit.jupiter.api.Test; + +class SimpleTest { @Test - public void testSum() { + void testSum() { int a = 1 + 1; assertEquals(2, a); } @Test - public void testString() { + void testString() { String str = "Hello world"; assertFalse(str.isEmpty()); } diff --git a/documentation/manual/working/javaGuide/main/tests/code/javaguide/tests/controllers/HomeController.java b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/controllers/HomeController.java similarity index 90% rename from documentation/manual/working/javaGuide/main/tests/code/javaguide/tests/controllers/HomeController.java rename to documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/controllers/HomeController.java index 03e972dc08b..419b10fae6f 100644 --- a/documentation/manual/working/javaGuide/main/tests/code/javaguide/tests/controllers/HomeController.java +++ b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/controllers/HomeController.java @@ -2,7 +2,7 @@ * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. */ -package javaguide.tests.controllers; +package javaguide.test.junit5.controllers; import play.mvc.*; diff --git a/documentation/manual/working/javaGuide/main/tests/code/tests/guice/Component.java b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/guice/Component.java similarity index 86% rename from documentation/manual/working/javaGuide/main/tests/code/tests/guice/Component.java rename to documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/guice/Component.java index 622193789ea..b7c13f1ef97 100644 --- a/documentation/manual/working/javaGuide/main/tests/code/tests/guice/Component.java +++ b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/guice/Component.java @@ -2,7 +2,7 @@ * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. */ -package javaguide.tests.guice; +package javaguide.test.junit5.guice; // #component public interface Component { diff --git a/documentation/manual/working/javaGuide/main/tests/code/tests/guice/ComponentModule.java b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/guice/ComponentModule.java similarity index 91% rename from documentation/manual/working/javaGuide/main/tests/code/tests/guice/ComponentModule.java rename to documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/guice/ComponentModule.java index 3a3ef8b9709..3fe3359c711 100644 --- a/documentation/manual/working/javaGuide/main/tests/code/tests/guice/ComponentModule.java +++ b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/guice/ComponentModule.java @@ -2,7 +2,7 @@ * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. */ -package javaguide.tests.guice; +package javaguide.test.junit5.guice; // #component-module import com.google.inject.AbstractModule; diff --git a/documentation/manual/working/javaGuide/main/tests/code/tests/guice/DefaultComponent.java b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/guice/DefaultComponent.java similarity index 89% rename from documentation/manual/working/javaGuide/main/tests/code/tests/guice/DefaultComponent.java rename to documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/guice/DefaultComponent.java index f7556e397e7..748c314a260 100644 --- a/documentation/manual/working/javaGuide/main/tests/code/tests/guice/DefaultComponent.java +++ b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/guice/DefaultComponent.java @@ -2,7 +2,7 @@ * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. */ -package javaguide.tests.guice; +package javaguide.test.junit5.guice; // #default-component public class DefaultComponent implements Component { diff --git a/documentation/manual/working/javaGuide/main/tests/code/tests/guice/JavaGuiceApplicationBuilderTest.java b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/guice/JavaGuiceApplicationBuilderTest.java similarity index 74% rename from documentation/manual/working/javaGuide/main/tests/code/tests/guice/JavaGuiceApplicationBuilderTest.java rename to documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/guice/JavaGuiceApplicationBuilderTest.java index 437ef1a6c2e..4820b09a7a4 100644 --- a/documentation/manual/working/javaGuide/main/tests/code/tests/guice/JavaGuiceApplicationBuilderTest.java +++ b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/guice/JavaGuiceApplicationBuilderTest.java @@ -2,28 +2,26 @@ * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. */ -package javaguide.tests.guice; +package javaguide.test.junit5.guice; +import static javaguide.test.junit5.FakeApplicationTest.Computer; +import static org.junit.jupiter.api.Assertions.*; +import static play.test.Helpers.*; + +import com.google.common.collect.ImmutableMap; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; -import com.google.common.collect.ImmutableMap; import java.io.File; import java.net.URL; import java.net.URLClassLoader; import java.util.Map; -import org.junit.Rule; -import org.junit.rules.ExpectedException; -import org.junit.Test; +import org.junit.jupiter.api.Test; + import play.Environment; import play.Mode; -import play.api.Configuration; import play.mvc.Result; +import router.Routes; -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.*; -import static play.test.Helpers.*; - -import static javaguide.tests.FakeApplicationTest.Computer; // #builder-imports import play.Application; @@ -43,12 +41,10 @@ import play.inject.guice.GuiceInjectorBuilder; // #injector-imports -public class JavaGuiceApplicationBuilderTest { - - @Rule public ExpectedException exception = ExpectedException.none(); +class JavaGuiceApplicationBuilderTest { @Test - public void setEnvironment() { + void setEnvironment() { ClassLoader classLoader = new URLClassLoader(new URL[0]); // #set-environment Application application = @@ -64,13 +60,13 @@ public void setEnvironment() { .build(); // #set-environment - assertThat(application.path(), equalTo(new File("path/to/app"))); - assert (application.isTest()); - assertThat(application.classloader(), sameInstance(classLoader)); + assertEquals(application.path(), new File("path/to/app")); + assertTrue(application.isTest()); + assertSame(application.classloader(), classLoader); } @Test - public void setEnvironmentValues() { + void setEnvironmentValues() { ClassLoader classLoader = new URLClassLoader(new URL[0]); // #set-environment-values Application application = @@ -88,13 +84,13 @@ public void setEnvironmentValues() { .build(); // #set-environment-values - assertThat(application.path(), equalTo(new File("path/to/app"))); - assert (application.isTest()); - assertThat(application.classloader(), sameInstance(classLoader)); + assertEquals(application.path(), new File("path/to/app")); + assertTrue(application.isTest()); + assertSame(application.classloader(), classLoader); } @Test - public void addConfiguration() { + void addConfiguration() { // #add-configuration Config extraConfig = ConfigFactory.parseMap(ImmutableMap.of("a", 1)); Map configMap = ImmutableMap.of("b", 2, "c", "three"); @@ -107,24 +103,26 @@ public void addConfiguration() { .build(); // #add-configuration - assertThat(application.config().getInt("a"), equalTo(1)); - assertThat(application.config().getInt("b"), equalTo(2)); - assertThat(application.config().getString("c"), equalTo("three")); - assertThat(application.config().getString("key"), equalTo("value")); + assertEquals(1, application.config().getInt("a")); + assertEquals(2, application.config().getInt("b")); + assertEquals("three", application.config().getString("c")); + assertEquals("value", application.config().getString("key")); } @Test - public void overrideConfiguration() { + void overrideConfiguration() { // #override-configuration Application application = new GuiceApplicationBuilder() .withConfigLoader(env -> ConfigFactory.load(env.classLoader())) .build(); + + assertNotNull(application); // #override-configuration } @Test - public void addBindings() { + void addBindings() { // #add-bindings Application application = new GuiceApplicationBuilder() @@ -133,12 +131,12 @@ public void addBindings() { .build(); // #add-bindings - assertThat( - application.injector().instanceOf(Component.class), instanceOf(DefaultComponent.class)); + Component component = application.injector().instanceOf(Component.class); + assertInstanceOf(DefaultComponent.class, component); } @Test - public void overrideBindings() { + void overrideBindings() { // #override-bindings Application application = new GuiceApplicationBuilder() @@ -153,12 +151,12 @@ public void overrideBindings() { application, () -> { Result result = route(application, fakeRequest(GET, "/")); - assertThat(contentAsString(result), equalTo("mock")); + assertEquals("mock", contentAsString(result)); }); } @Test - public void loadModules() { + void loadModules() { // #load-modules Application application = new GuiceApplicationBuilder() @@ -173,12 +171,12 @@ public void loadModules() { .build(); // #load-modules - assertThat( - application.injector().instanceOf(Component.class), instanceOf(DefaultComponent.class)); + Component component = application.injector().instanceOf(Component.class); + assertInstanceOf(DefaultComponent.class, component); } @Test - public void disableModules() { + void disableModules() { // #disable-modules Application application = new GuiceApplicationBuilder() @@ -188,12 +186,13 @@ public void disableModules() { .build(); // #disable-modules - exception.expect(com.google.inject.ConfigurationException.class); - application.injector().instanceOf(Component.class); + assertThrowsExactly( + com.google.inject.ConfigurationException.class, + () -> application.injector().instanceOf(Component.class)); } @Test - public void injectorBuilder() { + void injectorBuilder() { // #injector-builder Injector injector = new GuiceInjectorBuilder() @@ -205,12 +204,12 @@ public void injectorBuilder() { Component component = injector.instanceOf(Component.class); // #injector-builder - assertThat(component, instanceOf(MockComponent.class)); + assertInstanceOf(MockComponent.class, component); } // #test-guiceapp @Test - public void findById() { + void findById() { ClassLoader classLoader = classLoader(); Application application = new GuiceApplicationBuilder() @@ -220,7 +219,7 @@ public void findById() { running( application, () -> { - Computer macintosh = Computer.findById(21l); + Computer macintosh = Computer.findById(21L); assertEquals("Macintosh", macintosh.name); assertEquals("1984-01-24", macintosh.introduced); }); diff --git a/documentation/manual/working/javaGuide/main/tests/code/tests/guice/MockComponent.java b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/guice/MockComponent.java similarity index 88% rename from documentation/manual/working/javaGuide/main/tests/code/tests/guice/MockComponent.java rename to documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/guice/MockComponent.java index f428c156272..30f0e95b90c 100644 --- a/documentation/manual/working/javaGuide/main/tests/code/tests/guice/MockComponent.java +++ b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/guice/MockComponent.java @@ -2,7 +2,7 @@ * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. */ -package javaguide.tests.guice; +package javaguide.test.junit5.guice; // #mock-component public class MockComponent implements Component { diff --git a/documentation/manual/working/javaGuide/main/tests/code/tests/guice/controllers/Application.java b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/guice/controllers/Application.java similarity index 84% rename from documentation/manual/working/javaGuide/main/tests/code/tests/guice/controllers/Application.java rename to documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/guice/controllers/Application.java index bfc2fe24096..34f3a22f9cc 100644 --- a/documentation/manual/working/javaGuide/main/tests/code/tests/guice/controllers/Application.java +++ b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/guice/controllers/Application.java @@ -2,9 +2,9 @@ * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. */ -package javaguide.tests.guice.controllers; +package javaguide.test.junit5.guice.controllers; -import javaguide.tests.guice.Component; +import javaguide.test.junit5.guice.Component; // #controller import play.mvc.*; diff --git a/documentation/manual/working/javaGuide/main/tests/code/javaguide/tests/index.scala.html b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/index.scala.html similarity index 100% rename from documentation/manual/working/javaGuide/main/tests/code/javaguide/tests/index.scala.html rename to documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/index.scala.html diff --git a/documentation/manual/working/javaGuide/main/tests/code/javaguide/tests/HamcrestTest.java b/documentation/manual/working/javaGuide/main/tests/code/javaguide/tests/HamcrestTest.java deleted file mode 100644 index 8c2a70d02f3..00000000000 --- a/documentation/manual/working/javaGuide/main/tests/code/javaguide/tests/HamcrestTest.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. - */ - -package javaguide.tests; - -// #test-hamcrest -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.assertThat; - -import org.junit.Test; - -public class HamcrestTest { - - @Test - public void testString() { - String str = "good"; - assertThat(str, allOf(equalTo("good"), startsWith("goo"))); - } -} -// #test-hamcrest diff --git a/documentation/manual/working/javaGuide/main/tests/code/javaguide/tests/InjectionTest.java b/documentation/manual/working/javaGuide/main/tests/code/javaguide/tests/InjectionTest.java deleted file mode 100644 index 4631a638df6..00000000000 --- a/documentation/manual/working/javaGuide/main/tests/code/javaguide/tests/InjectionTest.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. - */ - -package javaguide.tests; - -import static org.junit.Assert.*; -import static play.test.Helpers.*; - -import com.google.inject.AbstractModule; -import com.google.inject.Guice; -import com.google.inject.Module; -import javax.inject.Inject; -import org.junit.After; -import org.junit.Before; -import play.Application; -import play.ApplicationLoader.Context; -import play.Environment; -import play.inject.guice.GuiceApplicationBuilder; -import play.inject.guice.GuiceApplicationLoader; -import play.test.Helpers; - -public class InjectionTest { - - // #test-injection - @Inject Application application; - - @Before - public void setup() { - Module testModule = - new AbstractModule() { - @Override - public void configure() { - // Install custom test binding here - } - }; - - GuiceApplicationBuilder builder = - new GuiceApplicationLoader() - .builder(new Context(Environment.simple())) - .overrides(testModule); - Guice.createInjector(builder.applicationModule()).injectMembers(this); - - Helpers.start(application); - } - - @After - public void teardown() { - Helpers.stop(application); - } - // #test-injection - -} From 52b219bc1efebc36d5934be052277318f3010f4a Mon Sep 17 00:00:00 2001 From: "H. Habighorst" Date: Fri, 14 Jul 2023 15:13:23 +0200 Subject: [PATCH 05/15] #11839: disable MiMa for PlayTestJunit4 / PlayTestJunit5 --- build.sbt | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/build.sbt b/build.sbt index 47470884966..f2d7538ff8a 100644 --- a/build.sbt +++ b/build.sbt @@ -201,6 +201,8 @@ lazy val PlayTestProject = PlayCrossBuiltProject("Play-Test", "testkit/play-test lazy val PlayTestJUnit4Project = PlayCrossBuiltProject("Play-Test-JUnit4", "testkit/play-test-junit4") .settings( + mimaPreviousArtifacts := Set.empty, + mimaFailOnNoPrevious := false, libraryDependencies ++= Seq(junit4, junit4Interface), libraryDependencies --= Seq(junit5, junit5Interface), (Test / parallelExecution) := false @@ -216,7 +218,9 @@ lazy val PlayTestJUnit4Project = PlayCrossBuiltProject("Play-Test-JUnit4", "test lazy val PlayTestJUnit5Project = PlayCrossBuiltProject("Play-Test-JUnit5", "testkit/play-test-junit5") .settings( - (Test / parallelExecution) := false + mimaPreviousArtifacts := Set.empty, + mimaFailOnNoPrevious := false, + (Test / parallelExecution) := false, ) .dependsOn( PlayGuiceProject, From dc59585a0c2c0da8d6442c149df2b8e5fd0cb171 Mon Sep 17 00:00:00 2001 From: "H. Habighorst" Date: Fri, 14 Jul 2023 17:06:45 +0200 Subject: [PATCH 06/15] #11839: remove duplicated license header --- .../manual/working/javaGuide/main/tests/JavaFunctionalTest.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/documentation/manual/working/javaGuide/main/tests/JavaFunctionalTest.md b/documentation/manual/working/javaGuide/main/tests/JavaFunctionalTest.md index e423e7b790c..00782f40631 100644 --- a/documentation/manual/working/javaGuide/main/tests/JavaFunctionalTest.md +++ b/documentation/manual/working/javaGuide/main/tests/JavaFunctionalTest.md @@ -1,7 +1,5 @@ - - # Writing functional tests Play provides a number of classes and convenience methods that assist with functional testing. From cc60c1642408bff4094d6a7e1d5711f4a36bd03b Mon Sep 17 00:00:00 2001 From: "H. Habighorst" Date: Fri, 14 Jul 2023 17:14:25 +0200 Subject: [PATCH 07/15] #11839: reformat code --- build.sbt | 6 +-- .../test/junit5/BrowserServerExtension.java | 51 +++++++++---------- .../ApplicationExtensionOverrideTest.java | 3 +- .../junit5/BrowserServerExtensionTest.java | 23 +++++---- .../java/play/test/junit5/HelpersTest.java | 32 ++++++------ 5 files changed, 57 insertions(+), 58 deletions(-) diff --git a/build.sbt b/build.sbt index f2d7538ff8a..98ddedfb195 100644 --- a/build.sbt +++ b/build.sbt @@ -202,7 +202,7 @@ lazy val PlayTestProject = PlayCrossBuiltProject("Play-Test", "testkit/play-test lazy val PlayTestJUnit4Project = PlayCrossBuiltProject("Play-Test-JUnit4", "testkit/play-test-junit4") .settings( mimaPreviousArtifacts := Set.empty, - mimaFailOnNoPrevious := false, + mimaFailOnNoPrevious := false, libraryDependencies ++= Seq(junit4, junit4Interface), libraryDependencies --= Seq(junit5, junit5Interface), (Test / parallelExecution) := false @@ -218,8 +218,8 @@ lazy val PlayTestJUnit4Project = PlayCrossBuiltProject("Play-Test-JUnit4", "test lazy val PlayTestJUnit5Project = PlayCrossBuiltProject("Play-Test-JUnit5", "testkit/play-test-junit5") .settings( - mimaPreviousArtifacts := Set.empty, - mimaFailOnNoPrevious := false, + mimaPreviousArtifacts := Set.empty, + mimaFailOnNoPrevious := false, (Test / parallelExecution) := false, ) .dependsOn( diff --git a/testkit/play-test-junit5/src/main/java/play/test/junit5/BrowserServerExtension.java b/testkit/play-test-junit5/src/main/java/play/test/junit5/BrowserServerExtension.java index 9963da7ccb2..cd310556c6a 100644 --- a/testkit/play-test-junit5/src/main/java/play/test/junit5/BrowserServerExtension.java +++ b/testkit/play-test-junit5/src/main/java/play/test/junit5/BrowserServerExtension.java @@ -5,7 +5,6 @@ package play.test.junit5; import java.util.Objects; - import org.junit.jupiter.api.extension.AfterAllCallback; import org.junit.jupiter.api.extension.BeforeAllCallback; import org.junit.jupiter.api.extension.ExtensionContext; @@ -14,36 +13,36 @@ public class BrowserServerExtension implements BeforeAllCallback, AfterAllCallback { - private final TestBrowser testBrowser; - private final TestServer testServer; + private final TestBrowser testBrowser; + private final TestServer testServer; - public BrowserServerExtension(TestBrowser testBrowser, TestServer testServer) { - this.testBrowser = testBrowser; - this.testServer = testServer; - } + public BrowserServerExtension(TestBrowser testBrowser, TestServer testServer) { + this.testBrowser = testBrowser; + this.testServer = testServer; + } - public TestBrowser getTestBrowser() { - return testBrowser; - } + public TestBrowser getTestBrowser() { + return testBrowser; + } - public TestServer getTestServer() { - return testServer; - } + public TestServer getTestServer() { + return testServer; + } - @Override - public void afterAll(ExtensionContext context) { - if (Objects.nonNull(testServer)) { - testServer.stop(); - } - if (Objects.nonNull(testBrowser)) { - testBrowser.quit(); - } + @Override + public void afterAll(ExtensionContext context) { + if (Objects.nonNull(testServer)) { + testServer.stop(); + } + if (Objects.nonNull(testBrowser)) { + testBrowser.quit(); } + } - @Override - public void beforeAll(ExtensionContext context) { - if (Objects.nonNull(testServer)) { - testServer.start(); - } + @Override + public void beforeAll(ExtensionContext context) { + if (Objects.nonNull(testServer)) { + testServer.start(); } + } } diff --git a/testkit/play-test-junit5/src/test/java/play/test/junit5/ApplicationExtensionOverrideTest.java b/testkit/play-test-junit5/src/test/java/play/test/junit5/ApplicationExtensionOverrideTest.java index 4bf6efa5c1c..d8e9d7598f9 100644 --- a/testkit/play-test-junit5/src/test/java/play/test/junit5/ApplicationExtensionOverrideTest.java +++ b/testkit/play-test-junit5/src/test/java/play/test/junit5/ApplicationExtensionOverrideTest.java @@ -15,8 +15,7 @@ class ApplicationExtensionOverrideTest { @RegisterExtension static ApplicationExtension applicationExtension = new ApplicationExtension( - new GuiceApplicationBuilder().configure("extraConfig", "valueForExtraConfig").build() - ); + new GuiceApplicationBuilder().configure("extraConfig", "valueForExtraConfig").build()); @Test void shouldHaveAnAppInstantiated() { diff --git a/testkit/play-test-junit5/src/test/java/play/test/junit5/BrowserServerExtensionTest.java b/testkit/play-test-junit5/src/test/java/play/test/junit5/BrowserServerExtensionTest.java index 5716ac4b937..046c6f4fa9f 100644 --- a/testkit/play-test-junit5/src/test/java/play/test/junit5/BrowserServerExtensionTest.java +++ b/testkit/play-test-junit5/src/test/java/play/test/junit5/BrowserServerExtensionTest.java @@ -13,17 +13,18 @@ import play.test.TestBrowser; class BrowserServerExtensionTest { - @RegisterExtension - static BrowserServerExtension browserServer = - new BrowserServerExtension(Helpers.testBrowser(8080), Helpers.testServer(8080, Helpers.fakeApplication())); + @RegisterExtension + static BrowserServerExtension browserServer = + new BrowserServerExtension( + Helpers.testBrowser(8080), Helpers.testServer(8080, Helpers.fakeApplication())); - @Test - void withBrowserShouldProvideABrowser() { - TestBrowser browser = browserServer.getTestBrowser(); + @Test + void withBrowserShouldProvideABrowser() { + TestBrowser browser = browserServer.getTestBrowser(); - assertNotNull(browser); - browser.goTo("/"); - assertNotNull(browser.pageSource()); - assertTrue(browser.pageSource().contains("Action Not Found")); - } + assertNotNull(browser); + browser.goTo("/"); + assertNotNull(browser.pageSource()); + assertTrue(browser.pageSource().contains("Action Not Found")); + } } diff --git a/testkit/play-test-junit5/src/test/java/play/test/junit5/HelpersTest.java b/testkit/play-test-junit5/src/test/java/play/test/junit5/HelpersTest.java index 81e3835e561..b1e703528f1 100644 --- a/testkit/play-test-junit5/src/test/java/play/test/junit5/HelpersTest.java +++ b/testkit/play-test-junit5/src/test/java/play/test/junit5/HelpersTest.java @@ -26,44 +26,44 @@ import scala.concurrent.Future; import scala.concurrent.duration.Duration; - class HelpersTest { +class HelpersTest { @Test - void shouldCreateASimpleFakeRequest() { + void shouldCreateASimpleFakeRequest() { Http.RequestImpl request = Helpers.fakeRequest().build(); assertEquals("GET", request.method()); assertEquals("/", request.path()); } @Test - void shouldCreateAFakeRequestWithMethodAndUri() { + void shouldCreateAFakeRequestWithMethodAndUri() { Http.RequestImpl request = Helpers.fakeRequest("POST", "/my-uri").build(); assertEquals("POST", request.method()); assertEquals("/my-uri", request.path()); } @Test - void shouldAddHostHeaderToFakeRequests() { + void shouldAddHostHeaderToFakeRequests() { Http.RequestImpl request = Helpers.fakeRequest().build(); assertEquals("localhost", request.host()); } @Test - void shouldCreateFakeApplicationsWithAnInMemoryDatabase() { + void shouldCreateFakeApplicationsWithAnInMemoryDatabase() { Application application = Helpers.fakeApplication(Helpers.inMemoryDatabase()); assertNotNull(application.config().getString("db.default.driver")); assertNotNull(application.config().getString("db.default.url")); } @Test - void shouldCreateFakeApplicationsWithAnNamedInMemoryDatabase() { + void shouldCreateFakeApplicationsWithAnNamedInMemoryDatabase() { Application application = Helpers.fakeApplication(Helpers.inMemoryDatabase("testDb")); assertNotNull(application.config().getString("db.testDb.driver")); assertNotNull(application.config().getString("db.testDb.url")); } @Test - void shouldCreateFakeApplicationsWithAnNamedInMemoryDatabaseAndConnectionOptions() { + void shouldCreateFakeApplicationsWithAnNamedInMemoryDatabaseAndConnectionOptions() { Map options = new HashMap<>(); options.put("username", "testUsername"); options.put("ttl", "10"); @@ -76,14 +76,14 @@ void shouldCreateFakeApplicationsWithAnNamedInMemoryDatabaseAndConnectionOptions } @Test - void shouldExtractContentAsBytesFromAResult() { + void shouldExtractContentAsBytesFromAResult() { Result result = Results.ok("Test content"); ByteString contentAsBytes = Helpers.contentAsBytes(result); assertEquals(ByteString.fromString("Test content"), contentAsBytes); } @Test - void shouldExtractContentAsBytesFromAResultUsingAMaterializer() throws Exception { + void shouldExtractContentAsBytesFromAResultUsingAMaterializer() throws Exception { ActorSystem actorSystem = ActorSystem.create("TestSystem"); try { @@ -99,28 +99,28 @@ void shouldExtractContentAsBytesFromAResultUsingAMaterializer() throws Exception } @Test - void shouldExtractContentAsBytesFromTwirlContent() { + void shouldExtractContentAsBytesFromTwirlContent() { Content content = Html.apply("Test content"); ByteString contentAsBytes = Helpers.contentAsBytes(content); assertEquals(ByteString.fromString("Test content"), contentAsBytes); } @Test - void shouldExtractContentAsStringFromTwirlContent() { + void shouldExtractContentAsStringFromTwirlContent() { Content content = Html.apply("Test content"); String contentAsString = Helpers.contentAsString(content); assertEquals("Test content", contentAsString); } @Test - void shouldExtractContentAsStringFromAResult() { + void shouldExtractContentAsStringFromAResult() { Result result = Results.ok("Test content"); String contentAsString = Helpers.contentAsString(result); assertEquals("Test content", contentAsString); } @Test - void shouldExtractContentAsStringFromAResultUsingAMaterializer() throws Exception { + void shouldExtractContentAsStringFromAResultUsingAMaterializer() throws Exception { ActorSystem actorSystem = ActorSystem.create("TestSystem"); try { @@ -136,7 +136,7 @@ void shouldExtractContentAsStringFromAResultUsingAMaterializer() throws Exceptio } @Test - void shouldSuccessfullyExecutePostRequestWithEmptyBody() { + void shouldSuccessfullyExecutePostRequestWithEmptyBody() { Http.RequestBuilder request = Helpers.fakeRequest("POST", "/uri"); Application app = Helpers.fakeApplication(); @@ -145,7 +145,7 @@ void shouldSuccessfullyExecutePostRequestWithEmptyBody() { } @Test - void shouldSuccessfullyExecutePostRequestWithMultipartFormData() { + void shouldSuccessfullyExecutePostRequestWithMultipartFormData() { Application app = Helpers.fakeApplication(); Map postParams = new java.util.HashMap<>(); postParams.put("key", new String[] {"value"}); @@ -156,7 +156,7 @@ void shouldSuccessfullyExecutePostRequestWithMultipartFormData() { } @Test - void shouldReturnProperHasBodyValueForFakeRequest() { + void shouldReturnProperHasBodyValueForFakeRequest() { // Does not set a Content-Length and also not a Transfer-Encoding header, sets null as body Http.Request request = Helpers.fakeRequest("POST", "/uri").build(); assertFalse(request.hasBody()); From 76009e8144379876bd96df80d13193f986f86704 Mon Sep 17 00:00:00 2001 From: "H. Habighorst" Date: Fri, 14 Jul 2023 17:46:18 +0200 Subject: [PATCH 08/15] #11839: fix wrong api links --- .../working/javaGuide/main/tests/JavaFunctionalTest.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/documentation/manual/working/javaGuide/main/tests/JavaFunctionalTest.md b/documentation/manual/working/javaGuide/main/tests/JavaFunctionalTest.md index 00782f40631..09bbfc56202 100644 --- a/documentation/manual/working/javaGuide/main/tests/JavaFunctionalTest.md +++ b/documentation/manual/working/javaGuide/main/tests/JavaFunctionalTest.md @@ -8,8 +8,8 @@ For scala code, helpers can be found in the [`play.test`](api/java/play/test/pac Depending on framework, additional helpers are provided: -- [JUnit 5](https://junit.org/junit5/): [`play.test.junit5`](api/play/test/junit5/package-summary.html) -- [JUnit 4](https://junit.org/junit4/): [`play.test.junit4`](api/play/test/junit4/package-summary.html) +- [JUnit 5](https://junit.org/junit5/): [`play.test.junit5`](api/java/play/test/junit5/package-summary.html) +- [JUnit 4](https://junit.org/junit4/): [`play.test.junit4`](api/java/play/test/junit4/package-summary.html) # [JUnit 5](https://junit.org/junit5/) test helpers @@ -51,7 +51,7 @@ Note that there are different ways to customize the `Application` creation when ## Testing with an application -To run JUnit 4 tests with an application, one can extend [`WithApplication`](api/play/test/junit4/WithApplication.html). +To run JUnit 4 tests with an application, one can extend [`WithApplication`](api/java/play/test/junit4/WithApplication.html). This will automatically ensure that an application is started and stopped for each test method: @@ -77,7 +77,7 @@ Sometimes you want to test the real HTTP stack from within your test. You can do @[test-server](code/javaguide/test/junit4/FunctionalTest.java) -Just as there exists a `WithApplication` class, there is also a [`WithServer`](api/play/test/junit4/WithBrowser.html) which you can extend to automatically start and stop a [`TestServer`](api/play/test/TestServer.html) for your tests: +Just as there exists a `WithApplication` class, there is also a [`WithServer`](api/java/play/test/junit4/WithBrowser.html) which you can extend to automatically start and stop a [`TestServer`](api/java/play/test/TestServer.html) for your tests: @[test-withserver](code/javaguide/test/junit4/ServerFunctionalTest.java) @@ -87,6 +87,6 @@ If you want to test your application from with a Web browser, you can use [Selen @[test-browser](code/javaguide/test/junit4/FunctionalTest.java) -And, of course there, is the [`WithBrowser`](api/play/test/junit4/WithBrowser.html) class to automatically open and close a browser for each test: +And, of course there, is the [`WithBrowser`](api/java/play/test/junit4/WithBrowser.html) class to automatically open and close a browser for each test: @[test-withbrowser](code/javaguide/test/junit4/BrowserFunctionalTest.java) From d980016764be32b31f322729a1e8e75ef358a92d Mon Sep 17 00:00:00 2001 From: "H. Habighorst" Date: Fri, 14 Jul 2023 21:23:24 +0200 Subject: [PATCH 09/15] #11839: documentation: migrate test code --- documentation/build.sbt | 2 + .../akka/typed/AkkaTypedDocTest.java | 27 ++--- .../code/detailedtopics/ThreadPoolsJava.java | 9 +- .../detailed/filters/FiltersTest.java | 18 +-- .../advanced/embedding/JavaEmbeddingPlay.java | 19 ++- .../advanced/extending/JavaExtendingPlay.java | 11 +- .../advanced/routing/JavaRoutingDsl.java | 54 ++++----- .../akka/code/javaguide/akka/JavaAkka.java | 23 ++-- .../async/code/javaguide/async/JavaAsync.java | 13 +- .../async/code/javaguide/async/JavaComet.java | 29 +++-- .../code/javaguide/async/JavaStream.java | 67 ++++++---- .../cache/code/javaguide/cache/JavaCache.java | 48 ++++---- .../code/javaguide/ehcache/JavaEhCache.java | 63 +++++----- .../javaguide/di/JavaDependencyInjection.java | 29 +++-- .../forms/code/javaguide/forms/JavaCsrf.java | 48 ++++---- .../forms/code/javaguide/forms/JavaForms.java | 114 ++++++++++-------- .../forms/JavaFormsDirectFieldAccess.java | 20 +-- .../http/code/javaguide/http/JavaActions.java | 74 ++++++------ .../code/javaguide/http/JavaBodyParsers.java | 107 ++++++++-------- .../http/JavaContentNegotiation.java | 25 ++-- .../code/javaguide/http/JavaResponse.java | 110 +++++++++-------- .../code/javaguide/http/JavaSessionFlash.java | 66 +++++----- .../i18n/code/javaguide/i18n/JavaI18N.java | 84 +++++++------ .../code/javaguide/json/JavaJsonActions.java | 72 ++++++----- .../code/javaguide/logging/JavaLogging.java | 11 +- .../main/tests/JavaTestingWithDatabases.md | 2 +- ...ts.routes => javaguide.test.junit4.routes} | 0 ...bt => javaguide.test.junit5.databases.sbt} | 0 ...tes => javaguide.test.junit5.guice.routes} | 0 .../tests/code/javaguide.test.junit5.routes | 4 + .../controllers/HomeController.java | 2 +- .../test/junit4/BrowserFunctionalTest.java | 3 +- .../javaguide/test/junit4/FunctionalTest.java | 7 +- .../test/junit4/ServerFunctionalTest.java | 1 + .../junit4/controllers/HomeController.java | 18 +++ .../javaguide/test/junit4/index.scala.html | 4 + .../javaguide/test/junit5/ControllerTest.java | 3 +- .../javaguide/test/junit5/DatabaseTest.java | 2 +- .../test/junit5/FakeApplicationTest.java | 2 +- .../javaguide/test/junit5/InjectionTest.java | 4 +- .../test/junit5/JavaTestingWithDatabases.java | 2 +- .../JavaGuiceApplicationBuilderTest.java | 2 +- .../main/upload/code/JavaFileUpload.java | 26 ++-- .../main/upload/code/JavaFileUploadTest.java | 20 +-- .../main/ws/code/javaguide/ws/Standalone.java | 4 +- .../javaguide/ws/StandaloneWithConfig.java | 2 +- 46 files changed, 683 insertions(+), 568 deletions(-) rename documentation/manual/working/javaGuide/main/tests/code/{javaguide.tests.routes => javaguide.test.junit4.routes} (100%) rename documentation/manual/working/javaGuide/main/tests/code/{javaguide.tests.databases.sbt => javaguide.test.junit5.databases.sbt} (100%) rename documentation/manual/working/javaGuide/main/tests/code/{javaguide.tests.guice.routes => javaguide.test.junit5.guice.routes} (100%) create mode 100644 documentation/manual/working/javaGuide/main/tests/code/javaguide.test.junit5.routes rename documentation/manual/working/javaGuide/main/tests/code/javaguide/{test/junit5 => }/controllers/HomeController.java (84%) create mode 100644 documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit4/controllers/HomeController.java create mode 100644 documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit4/index.scala.html diff --git a/documentation/build.sbt b/documentation/build.sbt index 564dd0d3f75..2cdaf0893f8 100644 --- a/documentation/build.sbt +++ b/documentation/build.sbt @@ -117,6 +117,8 @@ lazy val main = Project("Play-Documentation", file(".")) playDocs, playProject("Play") % "test", playProject("Play-Specs2") % "test", + playProject("Play-Test-JUnit4") % "test", + playProject("Play-Test-JUnit5") % "test", playProject("Play-Java") % "test", playProject("Play-Java-Forms") % "test", playProject("Play-Java-JPA") % "test", diff --git a/documentation/manual/working/commonGuide/akka/code/javaguide/akka/typed/AkkaTypedDocTest.java b/documentation/manual/working/commonGuide/akka/code/javaguide/akka/typed/AkkaTypedDocTest.java index e5e58442d25..4b146477169 100644 --- a/documentation/manual/working/commonGuide/akka/code/javaguide/akka/typed/AkkaTypedDocTest.java +++ b/documentation/manual/working/commonGuide/akka/code/javaguide/akka/typed/AkkaTypedDocTest.java @@ -4,12 +4,11 @@ package javaguide.akka.typed; -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.assertNotNull; import com.google.inject.Module; import java.util.Collections; -import org.junit.Test; +import org.junit.jupiter.api.Test; import play.ApplicationLoader; import play.Environment; import play.inject.Injector; @@ -17,36 +16,36 @@ public final class AkkaTypedDocTest { @Test - public void runtime_DI_support_for_OO_style_typed_actors() { + void runtime_DI_support_for_OO_style_typed_actors() { Module module = new javaguide.akka.typed.oo.AppModule(); GuiceApplicationBuilder builder = new GuiceApplicationBuilder().bindings(module); Injector injector = builder.configure("my.config", "foo").injector(); javaguide.akka.typed.oo.Main main = injector.instanceOf(javaguide.akka.typed.oo.Main.class); - assertThat(main.helloActor, notNullValue()); - assertThat(main.configuredActor, notNullValue()); + assertNotNull(main.helloActor); + assertNotNull(main.configuredActor); } @Test - public void runtime_DI_support_for_multi_instance_OO_style_typed_actors() { + void runtime_DI_support_for_multi_instance_OO_style_typed_actors() { Module module = new javaguide.akka.typed.oo.multi.AppModule(); GuiceApplicationBuilder builder = new GuiceApplicationBuilder().bindings(module); Injector injector = builder.configure("my.config", "foo").injector(); javaguide.akka.typed.oo.multi.Main main = injector.instanceOf(javaguide.akka.typed.oo.multi.Main.class); - assertThat(main.helloActor1, notNullValue()); - assertThat(main.helloActor2, notNullValue()); - assertThat(main.configuredActor1, notNullValue()); - assertThat(main.configuredActor2, notNullValue()); + assertNotNull(main.helloActor1); + assertNotNull(main.helloActor2); + assertNotNull(main.configuredActor1); + assertNotNull(main.configuredActor2); } @Test - public void compile_time_DI_without_support_works() { + void compile_time_DI_without_support_works() { // A sanity-check of what compile-time DI looks like Environment environment = Environment.simple(); ApplicationLoader.Context context = ApplicationLoader.create(environment, Collections.singletonMap("my.config", "foo")); javaguide.akka.typed.oo.Main main = new javaguide.akka.typed.oo.AppComponents(context).main; - assertThat(main.helloActor, notNullValue()); - assertThat(main.configuredActor, notNullValue()); + assertNotNull(main.helloActor); + assertNotNull(main.configuredActor); } } diff --git a/documentation/manual/working/commonGuide/configuration/code/detailedtopics/ThreadPoolsJava.java b/documentation/manual/working/commonGuide/configuration/code/detailedtopics/ThreadPoolsJava.java index eeec4d393fa..0413b8064ca 100644 --- a/documentation/manual/working/commonGuide/configuration/code/detailedtopics/ThreadPoolsJava.java +++ b/documentation/manual/working/commonGuide/configuration/code/detailedtopics/ThreadPoolsJava.java @@ -4,17 +4,16 @@ package detailedtopics; -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import static play.test.Helpers.*; -import org.junit.Test; +import org.junit.jupiter.api.Test; import play.Application; public class ThreadPoolsJava { @Test - public void usingAppClassLoader() throws Exception { + void usingAppClassLoader() throws Exception { final Application app = fakeApplication(); running( app, @@ -24,7 +23,7 @@ public void usingAppClassLoader() throws Exception { // #using-app-classloader Class myClass = app.classloader().loadClass(myClassName); // #using-app-classloader - assertThat(myClass, notNullValue()); + assertNotNull(myClass); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } diff --git a/documentation/manual/working/commonGuide/filters/code/javaguide/detailed/filters/FiltersTest.java b/documentation/manual/working/commonGuide/filters/code/javaguide/detailed/filters/FiltersTest.java index 457269a70b8..43b6290e354 100644 --- a/documentation/manual/working/commonGuide/filters/code/javaguide/detailed/filters/FiltersTest.java +++ b/documentation/manual/working/commonGuide/filters/code/javaguide/detailed/filters/FiltersTest.java @@ -7,21 +7,25 @@ import static play.test.Helpers.GET; import static play.test.Helpers.POST; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import play.Application; import play.api.test.CSRFTokenHelper; import play.mvc.Http; import play.mvc.Results; import play.routing.Router; import play.routing.RoutingDsl; import play.test.Helpers; -import play.test.WithApplication; +import play.test.junit5.ApplicationExtension; -public class FiltersTest extends WithApplication { +public class FiltersTest { + + static ApplicationExtension appExtension = new ApplicationExtension(Helpers.fakeApplication()); + static Application app = appExtension.getApplication(); @Test - public void testRequestBuilder() { + void testRequestBuilder() { Router router = - new RoutingDsl(instanceOf(play.mvc.BodyParser.Default.class)) + new RoutingDsl(app.injector().instanceOf(play.mvc.BodyParser.Default.class)) .GET("/xx/Kiwi") .routingTo(request -> Results.ok("success")) .build(); @@ -38,9 +42,9 @@ public void testRequestBuilder() { } @Test - public void test() { + void test() { Router router = - new RoutingDsl(instanceOf(play.mvc.BodyParser.Default.class)) + new RoutingDsl(app.injector().instanceOf(play.mvc.BodyParser.Default.class)) .POST("/xx/Kiwi") .routingTo(request -> Results.ok("success")) .build(); diff --git a/documentation/manual/working/javaGuide/advanced/embedding/code/javaguide/advanced/embedding/JavaEmbeddingPlay.java b/documentation/manual/working/javaGuide/advanced/embedding/code/javaguide/advanced/embedding/JavaEmbeddingPlay.java index 9ea37f748ce..04f045594be 100644 --- a/documentation/manual/working/javaGuide/advanced/embedding/code/javaguide/advanced/embedding/JavaEmbeddingPlay.java +++ b/documentation/manual/working/javaGuide/advanced/embedding/code/javaguide/advanced/embedding/JavaEmbeddingPlay.java @@ -6,7 +6,7 @@ import java.io.IOException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import play.libs.ws.WSClient; import play.libs.ws.WSResponse; @@ -21,13 +21,12 @@ import static play.mvc.Controller.*; // #imports -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; public class JavaEmbeddingPlay { @Test - public void simple() throws Exception { + void simple() throws Exception { // #simple Server server = Server.forRouter( @@ -46,9 +45,7 @@ public void simple() throws Exception { ws.url("http://localhost:" + server.httpPort() + "/hello/world").get(); // #http-port try { - assertThat( - response.toCompletableFuture().get(10, TimeUnit.SECONDS).getBody(), - equalTo("Hello world")); + assertEquals("Hello world", response.toCompletableFuture().get(10, TimeUnit.SECONDS).getBody()); } catch (Exception e) { throw new RuntimeException(e); } @@ -61,7 +58,7 @@ public void simple() throws Exception { } @Test - public void config() throws Exception { + void config() throws Exception { // #config Server server = Server.forRouter( @@ -76,13 +73,13 @@ public void config() throws Exception { withClient( ws -> { try { - assertThat( + assertEquals( + "Hello world", ws.url("http://localhost:" + server.httpPort() + "/hello/world") .get() .toCompletableFuture() .get(10, TimeUnit.SECONDS) - .getBody(), - equalTo("Hello world")); + .getBody()); } catch (Exception e) { throw new RuntimeException(e); } diff --git a/documentation/manual/working/javaGuide/advanced/extending/code/javaguide/advanced/extending/JavaExtendingPlay.java b/documentation/manual/working/javaGuide/advanced/extending/code/javaguide/advanced/extending/JavaExtendingPlay.java index fdd2e17e505..b024cdb2e3e 100644 --- a/documentation/manual/working/javaGuide/advanced/extending/code/javaguide/advanced/extending/JavaExtendingPlay.java +++ b/documentation/manual/working/javaGuide/advanced/extending/code/javaguide/advanced/extending/JavaExtendingPlay.java @@ -4,10 +4,9 @@ package javaguide.advanced.extending; -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; -import org.junit.Test; +import org.junit.jupiter.api.Test; import play.Application; import play.inject.guice.GuiceApplicationBuilder; import play.libs.ws.WSClient; @@ -15,7 +14,7 @@ public class JavaExtendingPlay { @Test - public void testModule() throws Exception { + void testModule() throws Exception { // #module-class-binding Application application = new GuiceApplicationBuilder().bindings(new MyModule()).build(); // #module-class-binding @@ -25,12 +24,12 @@ public void testModule() throws Exception { } @Test - public void testOverride() throws Exception { + void testOverride() throws Exception { // #builtin-module-overrides Application application = new GuiceApplicationBuilder().overrides(new MyWSModule()).build(); // #builtin-module-overrides WSClient wsClient = application.injector().instanceOf(WSClient.class); - assertThat(wsClient, instanceOf(MyWSClient.class)); + assertInstanceOf(MyWSClient.class, wsClient); } } diff --git a/documentation/manual/working/javaGuide/advanced/routing/code/javaguide/advanced/routing/JavaRoutingDsl.java b/documentation/manual/working/javaGuide/advanced/routing/code/javaguide/advanced/routing/JavaRoutingDsl.java index 79c1099ed42..8f7a1b6c21c 100644 --- a/documentation/manual/working/javaGuide/advanced/routing/code/javaguide/advanced/routing/JavaRoutingDsl.java +++ b/documentation/manual/working/javaGuide/advanced/routing/code/javaguide/advanced/routing/JavaRoutingDsl.java @@ -4,8 +4,8 @@ package javaguide.advanced.routing; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; // #imports import javax.inject.Inject; @@ -22,45 +22,43 @@ // #imports import play.mvc.Result; -import play.test.WithApplication; +import play.test.junit5.ApplicationExtension; +import play.Application; -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import static play.test.Helpers.*; -public class JavaRoutingDsl extends WithApplication { +public class JavaRoutingDsl { - private RoutingDsl routingDsl; + static ApplicationExtension appExtension = new ApplicationExtension(fakeApplication()); + static Application app = appExtension.getApplication(); + static RoutingDsl routingDsl; - @Before - public void initializeRoutingDsl() { - this.routingDsl = app.injector().instanceOf(RoutingDsl.class); + @BeforeAll + static void initializeRoutingDsl() { + routingDsl = app.injector().instanceOf(RoutingDsl.class); } @Test - public void simple() { + void simple() { // #simple - Router router = - routingDsl.GET("/hello/:to").routingTo((request, to) -> ok("Hello " + to)).build(); + Router router = routingDsl.GET("/hello/:to").routingTo((request, to) -> ok("Hello " + to)).build(); // #simple - assertThat(makeRequest(router, "GET", "/hello/world"), equalTo("Hello world")); + assertEquals("Hello world", makeRequest(router, "GET", "/hello/world")); } @Test - public void fullPath() { + void fullPath() { // #full-path - Router router = - routingDsl.GET("/assets/*file").routingTo((request, file) -> ok("Serving " + file)).build(); + Router router = routingDsl.GET("/assets/*file").routingTo((request, file) -> ok("Serving " + file)).build(); // #full-path - assertThat( - makeRequest(router, "GET", "/assets/javascripts/main.js"), - equalTo("Serving javascripts/main.js")); + assertEquals("Serving javascripts/main.js", makeRequest(router, "GET", "/assets/javascripts/main.js")); } @Test - public void regexp() { + void regexp() { // #regexp Router router = routingDsl @@ -69,11 +67,11 @@ public void regexp() { .build(); // #regexp - assertThat(makeRequest(router, "GET", "/api/items/23"), equalTo("Getting item 23")); + assertEquals("Getting item 23", makeRequest(router, "GET", "/api/items/23")); } @Test - public void integer() { + void integer() { // #integer Router router = routingDsl @@ -82,11 +80,11 @@ public void integer() { .build(); // #integer - assertThat(makeRequest(router, "GET", "/api/items/23"), equalTo("Getting item 23")); + assertEquals("Getting item 23", makeRequest(router, "GET", "/api/items/23")); } @Test - public void async() { + void async() { // #async Router router = routingDsl @@ -97,7 +95,7 @@ public void async() { .build(); // #async - assertThat(makeRequest(router, "GET", "/api/items/23"), equalTo("Getting item 23")); + assertEquals("Getting item 23", makeRequest(router, "GET", "/api/items/23")); } private String makeRequest(Router router, String method, String path) { @@ -122,7 +120,7 @@ public MyComponent(RoutingDsl routing) { // #inject @Test - public void createNewRoutingDsl() { + void createNewRoutingDsl() { play.mvc.BodyParser.Default bodyParser = app.injector().instanceOf(play.mvc.BodyParser.Default.class); @@ -132,6 +130,6 @@ public void createNewRoutingDsl() { Router router = routingDsl.GET("/hello/:to").routingTo((request, to) -> ok("Hello " + to)).build(); - assertThat(makeRequest(router, "GET", "/hello/world"), equalTo("Hello world")); + assertEquals("Hello world", makeRequest(router, "GET", "/hello/world")); } } diff --git a/documentation/manual/working/javaGuide/main/akka/code/javaguide/akka/JavaAkka.java b/documentation/manual/working/javaGuide/main/akka/code/javaguide/akka/JavaAkka.java index b3108152f99..d0389462514 100644 --- a/documentation/manual/working/javaGuide/main/akka/code/javaguide/akka/JavaAkka.java +++ b/documentation/manual/working/javaGuide/main/akka/code/javaguide/akka/JavaAkka.java @@ -5,8 +5,7 @@ package javaguide.akka; import static akka.pattern.Patterns.ask; -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import static play.test.Helpers.*; import akka.actor.*; @@ -14,7 +13,7 @@ import java.util.concurrent.*; import javaguide.testhelpers.MockJavaAction; import javaguide.testhelpers.MockJavaActionHelper; -import org.junit.Test; +import org.junit.jupiter.api.Test; import play.Application; import play.core.j.JavaHandlerComponents; import play.inject.guice.GuiceApplicationBuilder; @@ -39,7 +38,7 @@ public Receive createReceive() { } @Test - public void testask() throws Exception { + void testask() throws Exception { Application app = fakeApplication(); running( app, @@ -51,7 +50,7 @@ public void testask() throws Exception { String message = contentAsString( controller.sayHello("world").toCompletableFuture().get(1, TimeUnit.SECONDS)); - assertThat(message, equalTo("Hello, world")); + assertEquals("Hello, world", message); } catch (Exception e) { throw new RuntimeException(e); } @@ -59,7 +58,7 @@ public void testask() throws Exception { } @Test - public void injected() throws Exception { + void injected() throws Exception { Application app = new GuiceApplicationBuilder() .bindings(new javaguide.akka.modules.MyModule()) @@ -75,7 +74,7 @@ public void injected() throws Exception { String message = contentAsString( controller.getConfig().toCompletableFuture().get(1, TimeUnit.SECONDS)); - assertThat(message, equalTo("foo")); + assertEquals("foo", message); } catch (Exception e) { throw new RuntimeException(e); } @@ -83,7 +82,7 @@ public void injected() throws Exception { } @Test - public void factoryinjected() throws Exception { + void factoryinjected() throws Exception { Application app = new GuiceApplicationBuilder() .bindings(new javaguide.akka.factorymodules.MyModule()) @@ -113,7 +112,7 @@ public void factoryinjected() throws Exception { java.time.Duration.ofMillis(1000))) .toCompletableFuture() .get(5, TimeUnit.SECONDS); - assertThat(message, equalTo("foo")); + assertEquals("foo", message); } catch (Exception e) { throw new RuntimeException(e); } @@ -121,14 +120,14 @@ public void factoryinjected() throws Exception { } @Test - public void conf() throws Exception { + void conf() throws Exception { Config config = ConfigFactory.parseURL(getClass().getResource("akka.conf")); scala.concurrent.Future future = ActorSystem.create("conf", config).terminate(); Await.ready(future, Duration.create("10s")); } @Test - public void async() throws Exception { + void async() throws Exception { Application app = fakeApplication(); running( app, @@ -142,7 +141,7 @@ public CompletionStage index() { }, fakeRequest(), app.asScala().materializer()); - assertThat(contentAsString(result), equalTo("Got 2")); + assertEquals("Got 2", contentAsString(result)); }); } } diff --git a/documentation/manual/working/javaGuide/main/async/code/javaguide/async/JavaAsync.java b/documentation/manual/working/javaGuide/main/async/code/javaguide/async/JavaAsync.java index a687d758f1e..5cee9a58574 100644 --- a/documentation/manual/working/javaGuide/main/async/code/javaguide/async/JavaAsync.java +++ b/documentation/manual/working/javaGuide/main/async/code/javaguide/async/JavaAsync.java @@ -5,9 +5,7 @@ package javaguide.async; import static java.time.temporal.ChronoUnit.SECONDS; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; +import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -16,14 +14,14 @@ import java.time.Duration; import java.util.concurrent.*; import javax.inject.Inject; -import org.junit.Test; +import org.junit.jupiter.api.Test; import play.libs.concurrent.*; import play.mvc.Result; public class JavaAsync { @Test - public void promiseWithTimeout() throws Exception { + void promiseWithTimeout() throws Exception { // #timeout class MyClass { @@ -62,7 +60,7 @@ public CompletionStage delayedResult() { .toCompletableFuture() .get(1, TimeUnit.SECONDS); final Double expected = Math.PI; - assertThat(actual, equalTo(expected)); + assertEquals(expected, actual); } @Test @@ -73,8 +71,7 @@ public void promisePi() throws Exception { CompletionStage promiseOfResult = promiseOfPIValue.thenApply(pi -> ok("PI value computed: " + pi)); // #promise-pi - assertThat( - promiseOfResult.toCompletableFuture().get(1, TimeUnit.SECONDS).status(), equalTo(200)); + assertEquals(200, promiseOfResult.toCompletableFuture().get(1, TimeUnit.SECONDS).status()); } @Test diff --git a/documentation/manual/working/javaGuide/main/async/code/javaguide/async/JavaComet.java b/documentation/manual/working/javaGuide/main/async/code/javaguide/async/JavaComet.java index 47d0b0b90a6..a8ea283785b 100644 --- a/documentation/manual/working/javaGuide/main/async/code/javaguide/async/JavaComet.java +++ b/documentation/manual/working/javaGuide/main/async/code/javaguide/async/JavaComet.java @@ -8,10 +8,11 @@ import com.fasterxml.jackson.databind.node.ObjectNode; import javaguide.testhelpers.MockJavaAction; import javaguide.testhelpers.MockJavaActionHelper; -import org.junit.Test; +import org.junit.jupiter.api.Test; // #comet-imports import akka.NotUsed; +import akka.stream.Materializer; import akka.stream.javadsl.Source; import play.core.j.JavaHandlerComponents; import play.libs.Comet; @@ -20,17 +21,21 @@ import play.mvc.Result; // #comet-imports -import play.test.WithApplication; - +import play.test.junit5.ApplicationExtension; +import play.Application; import java.util.Arrays; import java.util.Collections; -import static org.hamcrest.CoreMatchers.containsString; -import static org.junit.Assert.assertThat; +import static org.junit.jupiter.api.Assertions.assertTrue; import static play.test.Helpers.contentAsString; import static play.test.Helpers.fakeRequest; +import static play.test.Helpers.fakeApplication; + +public class JavaComet { -public class JavaComet extends WithApplication { + static ApplicationExtension appExtension = new ApplicationExtension(fakeApplication()); + static Application app = appExtension.getApplication(); + static Materializer mat = appExtension.getMaterializer(); public static class Controller1 extends MockJavaAction { @@ -63,7 +68,7 @@ public static Result index() { } @Test - public void foreverIframe() { + void foreverIframe() { String content = contentAsString( MockJavaActionHelper.call( @@ -71,13 +76,13 @@ public void foreverIframe() { fakeRequest(), mat), mat); - assertThat(content, containsString("")); - assertThat(content, containsString("")); - assertThat(content, containsString("")); + assertTrue(content.contains("")); + assertTrue(content.contains("")); + assertTrue(content.contains("")); } @Test - public void foreverIframeWithJson() { + void foreverIframeWithJson() { String content = contentAsString( MockJavaActionHelper.call( @@ -85,6 +90,6 @@ public void foreverIframeWithJson() { fakeRequest(), mat), mat); - assertThat(content, containsString("")); + assertTrue(content.contains("")); } } diff --git a/documentation/manual/working/javaGuide/main/async/code/javaguide/async/JavaStream.java b/documentation/manual/working/javaGuide/main/async/code/javaguide/async/JavaStream.java index eaa58314396..adeb1a3ce3c 100644 --- a/documentation/manual/working/javaGuide/main/async/code/javaguide/async/JavaStream.java +++ b/documentation/manual/working/javaGuide/main/async/code/javaguide/async/JavaStream.java @@ -5,12 +5,12 @@ package javaguide.async; import static javaguide.testhelpers.MockJavaActionHelper.call; -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import static play.test.Helpers.*; import akka.NotUsed; import akka.actor.Status; +import akka.stream.Materializer; import akka.stream.OverflowStrategy; import akka.stream.javadsl.FileIO; import akka.stream.javadsl.Source; @@ -20,21 +20,29 @@ import java.util.Collections; import java.util.Optional; import javaguide.testhelpers.MockJavaAction; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import play.Application; import play.core.j.JavaHandlerComponents; import play.http.HttpEntity; import play.mvc.ResponseHeader; import play.mvc.Result; -import play.test.WithApplication; +import play.test.junit5.ApplicationExtension; -public class JavaStream extends WithApplication { +public class JavaStream { + + static ApplicationExtension appExtension = new ApplicationExtension(fakeApplication()); + static Application app = appExtension.getApplication(); + static Materializer mat = appExtension.getMaterializer(); @Test - public void byDefault() { - assertThat( + void byDefault() { + assertEquals( + "Hello World", contentAsString( - call(new Controller1(instanceOf(JavaHandlerComponents.class)), fakeRequest(), mat)), - equalTo("Hello World")); + call( + new Controller1(app.injector().instanceOf(JavaHandlerComponents.class)), + fakeRequest(), + mat))); } public static class Controller1 extends MockJavaAction { @@ -51,14 +59,15 @@ public Result index() { } @Test - public void byDefaultWithHttpEntity() { - assertThat( + void byDefaultWithHttpEntity() { + assertEquals( + "Hello World", contentAsString( call( - new ControllerWithHttpEntity(instanceOf(JavaHandlerComponents.class)), + new ControllerWithHttpEntity( + app.injector().instanceOf(JavaHandlerComponents.class)), fakeRequest(), - mat)), - equalTo("Hello World")); + mat))); } public static class ControllerWithHttpEntity extends MockJavaAction { @@ -130,7 +139,7 @@ public Result index() { } @Test - public void serveFile() throws Exception { + void serveFile() throws Exception { File file = new File("/tmp/fileToServe.pdf"); file.deleteOnExit(); try (OutputStream os = java.nio.file.Files.newOutputStream(file.toPath())) { @@ -139,9 +148,12 @@ public void serveFile() throws Exception { throw new RuntimeException(e); } Result result = - call(new Controller2(instanceOf(JavaHandlerComponents.class)), fakeRequest(), mat); - assertThat(contentAsString(result, mat), equalTo("hi")); - assertThat(result.body().contentLength(), equalTo(Optional.of(2L))); + call( + new Controller2(app.injector().instanceOf(JavaHandlerComponents.class)), + fakeRequest(), + mat); + assertEquals("hi", contentAsString(result, mat)); + assertEquals(Optional.of(2L), result.body().contentLength()); file.delete(); } @@ -185,13 +197,15 @@ public Result index() { } @Test - public void inputStream() { + void inputStream() { String content = contentAsString( - call(new Controller3(instanceOf(JavaHandlerComponents.class)), fakeRequest(), mat), + call( + new Controller3(app.injector().instanceOf(JavaHandlerComponents.class)), + fakeRequest(), + mat), mat); - // Wait until results refactoring is merged, then this will work - // assertThat(content, containsString("hello")); + assertTrue(content.contains("hello")); } private static InputStream getDynamicStreamSomewhere() { @@ -213,12 +227,15 @@ public Result index() { } @Test - public void chunked() { + void chunked() { String content = contentAsString( - call(new Controller4(instanceOf(JavaHandlerComponents.class)), fakeRequest(), mat), + call( + new Controller4(app.injector().instanceOf(JavaHandlerComponents.class)), + fakeRequest(), + mat), mat); - assertThat(content, equalTo("kikifoobar")); + assertEquals("kikifoobar", content); } public static class Controller4 extends MockJavaAction { diff --git a/documentation/manual/working/javaGuide/main/cache/code/javaguide/cache/JavaCache.java b/documentation/manual/working/javaGuide/main/cache/code/javaguide/cache/JavaCache.java index c2eca82850a..881e03413f2 100644 --- a/documentation/manual/working/javaGuide/main/cache/code/javaguide/cache/JavaCache.java +++ b/documentation/manual/working/javaGuide/main/cache/code/javaguide/cache/JavaCache.java @@ -5,45 +5,48 @@ package javaguide.cache; import static javaguide.testhelpers.MockJavaActionHelper.call; -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import static play.test.Helpers.*; import akka.Done; +import akka.stream.Materializer; import com.google.common.collect.ImmutableMap; import java.util.Collections; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import javaguide.testhelpers.MockJavaAction; -import org.junit.Test; +import org.junit.jupiter.api.Test; import play.Application; import play.cache.AsyncCacheApi; import play.cache.Cached; import play.core.j.JavaHandlerComponents; import play.mvc.*; -import play.test.WithApplication; +import play.test.junit5.ApplicationExtension; -public class JavaCache extends WithApplication { +public class JavaCache { - @Override - protected Application provideApplication() { - return fakeApplication( - ImmutableMap.of("play.cache.bindCaches", Collections.singletonList("session-cache"))); - } + static ApplicationExtension appExtension = + new ApplicationExtension( + fakeApplication( + ImmutableMap.of( + "play.cache.bindCaches", Collections.singletonList("session-cache")))); + static Application app = appExtension.getApplication(); + static Materializer mat = appExtension.getMaterializer(); private class News {} @Test - public void inject() { + void inject() { // Check that we can instantiate it - app.injector().instanceOf(javaguide.cache.inject.Application.class); + assertDoesNotThrow(() -> app.injector().instanceOf(javaguide.cache.inject.Application.class)); // Check that we can instantiate the qualified one - app.injector().instanceOf(javaguide.cache.qualified.Application.class); + assertDoesNotThrow( + () -> app.injector().instanceOf(javaguide.cache.qualified.Application.class)); } @Test - public void simple() { + void simple() { AsyncCacheApi cache = app.injector().instanceOf(AsyncCacheApi.class); News frontPageNews = new News(); @@ -63,12 +66,12 @@ public void simple() { // #get CompletionStage> news = cache.get("item.key"); // #get - assertThat(block(news).get(), equalTo(frontPageNews)); + assertEquals(frontPageNews, block(news).get()); // #get-or-else CompletionStage maybeCached = cache.getOrElseUpdate("item.key", this::lookUpFrontPageNews); // #get-or-else - assertThat(block(maybeCached), equalTo(frontPageNews)); + assertEquals(frontPageNews, block(maybeCached)); { // #remove CompletionStage result = cache.remove("item.key"); @@ -79,7 +82,7 @@ public void simple() { // #removeAll block(result); } - assertThat(cache.sync().get("item.key"), equalTo(Optional.empty())); + assertEquals(Optional.empty(), cache.sync().get("item.key")); } private CompletionStage lookUpFrontPageNews() { @@ -101,19 +104,20 @@ public Result index() { } @Test - public void http() { + void http() { AsyncCacheApi cache = app.injector().instanceOf(AsyncCacheApi.class); - Controller1 controller1 = new Controller1(instanceOf(JavaHandlerComponents.class)); + Controller1 controller1 = + new Controller1(app.injector().instanceOf(JavaHandlerComponents.class)); - assertThat(contentAsString(call(controller1, fakeRequest(), mat)), equalTo("Hello world")); + assertEquals("Hello world", contentAsString(call(controller1, fakeRequest(), mat))); - assertThat(block(cache.get("homePage")).get(), notNullValue()); + assertNotNull(block(cache.get("homePage")).get()); // Set a new value to the cache key. We are blocking to ensure // the test will continue only when the value set is done. block(cache.set("homePage", Results.ok("something else"))); - assertThat(contentAsString(call(controller1, fakeRequest(), mat)), equalTo("something else")); + assertEquals("something else", contentAsString(call(controller1, fakeRequest(), mat))); } private static T block(CompletionStage stage) { diff --git a/documentation/manual/working/javaGuide/main/cache/code/javaguide/ehcache/JavaEhCache.java b/documentation/manual/working/javaGuide/main/cache/code/javaguide/ehcache/JavaEhCache.java index 5c121d25e3b..3ae51aa1293 100755 --- a/documentation/manual/working/javaGuide/main/cache/code/javaguide/ehcache/JavaEhCache.java +++ b/documentation/manual/working/javaGuide/main/cache/code/javaguide/ehcache/JavaEhCache.java @@ -5,46 +5,49 @@ package javaguide.ehcache; import static javaguide.testhelpers.MockJavaActionHelper.call; -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import static play.test.Helpers.*; import akka.Done; +import akka.stream.Materializer; import com.google.common.collect.ImmutableMap; import java.util.Collections; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import javaguide.testhelpers.MockJavaAction; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import play.Application; import play.cache.AsyncCacheApi; import play.cache.Cached; import play.core.j.JavaHandlerComponents; import play.mvc.*; -import play.test.WithApplication; +import play.test.junit5.ApplicationExtension; -public class JavaEhCache extends WithApplication { +public class JavaEhCache { - @Override - protected Application provideApplication() { - return fakeApplication( - ImmutableMap.of("play.cache.bindCaches", Collections.singletonList("session-cache"))); - } + static ApplicationExtension appExtension = + new ApplicationExtension( + fakeApplication( + ImmutableMap.of( + "play.cache.bindCaches", Collections.singletonList("session-cache")))); + static Application app = appExtension.getApplication(); + static Materializer mat = appExtension.getMaterializer(); private class News {} @Test - public void inject() { + void inject() { // Check that we can instantiate it - app.injector().instanceOf(javaguide.cache.inject.Application.class); + assertDoesNotThrow(() -> app.injector().instanceOf(javaguide.cache.inject.Application.class)); // Check that we can instantiate the qualified one - app.injector().instanceOf(javaguide.cache.qualified.Application.class); + assertDoesNotThrow( + () -> app.injector().instanceOf(javaguide.cache.qualified.Application.class)); } @Test - public void simple() { + void simple() { AsyncCacheApi cache = app.injector().instanceOf(AsyncCacheApi.class); News frontPageNews = new News(); @@ -64,12 +67,12 @@ public void simple() { // #get CompletionStage> news = cache.get("item.key"); // #get - assertThat(block(news).get(), equalTo(frontPageNews)); + assertEquals(frontPageNews, block(news).get()); // #get-or-else CompletionStage maybeCached = cache.getOrElseUpdate("item.key", this::lookUpFrontPageNews); // #get-or-else - assertThat(block(maybeCached), equalTo(frontPageNews)); + assertEquals(frontPageNews, block(maybeCached)); { // #remove CompletionStage result = cache.remove("item.key"); @@ -80,7 +83,7 @@ public void simple() { // #removeAll block(result); } - assertThat(cache.sync().get("item.key"), equalTo(Optional.empty())); + assertEquals(Optional.empty(), cache.sync().get("item.key")); } private CompletionStage lookUpFrontPageNews() { @@ -101,21 +104,27 @@ public Result index() { // #http } - @Ignore + @Disabled("Flaky EHCache test") @Test - public void http() { + void http() { AsyncCacheApi cache = app.injector().instanceOf(AsyncCacheApi.class); - assertThat( + assertEquals( + "Hello world", contentAsString( - call(new Controller1(instanceOf(JavaHandlerComponents.class)), fakeRequest(), mat)), - equalTo("Hello world")); - assertThat(cache.sync().get("homePage").get(), notNullValue()); + call( + new Controller1(app.injector().instanceOf(JavaHandlerComponents.class)), + fakeRequest(), + mat))); + assertNotNull(cache.sync().get("homePage").get()); cache.set("homePage", Results.ok("something else")); - assertThat( + assertEquals( + "something else", contentAsString( - call(new Controller1(instanceOf(JavaHandlerComponents.class)), fakeRequest(), mat)), - equalTo("something else")); + call( + new Controller1(app.injector().instanceOf(JavaHandlerComponents.class)), + fakeRequest(), + mat))); } private static T block(CompletionStage stage) { diff --git a/documentation/manual/working/javaGuide/main/dependencyinjection/code/javaguide/di/JavaDependencyInjection.java b/documentation/manual/working/javaGuide/main/dependencyinjection/code/javaguide/di/JavaDependencyInjection.java index c62cae03a84..8d707ed3824 100644 --- a/documentation/manual/working/javaGuide/main/dependencyinjection/code/javaguide/di/JavaDependencyInjection.java +++ b/documentation/manual/working/javaGuide/main/dependencyinjection/code/javaguide/di/JavaDependencyInjection.java @@ -4,39 +4,44 @@ package javaguide.di; -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; +import static play.test.Helpers.*; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import play.Application; import play.test.*; +import play.test.junit5.ApplicationExtension; -public class JavaDependencyInjection extends WithApplication { +public class JavaDependencyInjection { + + static ApplicationExtension appExtension = new ApplicationExtension(fakeApplication()); + static Application app = appExtension.getApplication(); @Test - public void fieldInjection() { + void fieldInjection() { assertNotNull(app.injector().instanceOf(javaguide.di.field.MyComponent.class)); } @Test - public void constructorInjection() { + void constructorInjection() { assertNotNull(app.injector().instanceOf(javaguide.di.constructor.MyComponent.class)); } @Test - public void singleton() { + void singleton() { app.injector().instanceOf(CurrentSharePrice.class).set(10); - assertThat(app.injector().instanceOf(CurrentSharePrice.class).get(), equalTo(10)); + assertEquals(10, app.injector().instanceOf(CurrentSharePrice.class).get()); } @Test - public void cleanup() { + void cleanup() { app.injector().instanceOf(MessageQueueConnection.class); - stopPlay(); + stop(app); assertTrue(MessageQueue.stopped); } @Test - public void implementedBy() { - assertThat(app.injector().instanceOf(Hello.class).sayHello("world"), equalTo("Hello world")); + void implementedBy() { + assertEquals("Hello world", app.injector().instanceOf(Hello.class).sayHello("world")); } } diff --git a/documentation/manual/working/javaGuide/main/forms/code/javaguide/forms/JavaCsrf.java b/documentation/manual/working/javaGuide/main/forms/code/javaguide/forms/JavaCsrf.java index 3b7c075356c..7d1b30dec17 100644 --- a/documentation/manual/working/javaGuide/main/forms/code/javaguide/forms/JavaCsrf.java +++ b/documentation/manual/working/javaGuide/main/forms/code/javaguide/forms/JavaCsrf.java @@ -5,18 +5,17 @@ package javaguide.forms; import static javaguide.testhelpers.MockJavaActionHelper.call; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; import static play.test.Helpers.*; +import akka.stream.Materializer; import java.util.Collections; import java.util.Optional; import java.util.regex.Matcher; import java.util.regex.Pattern; import javaguide.testhelpers.MockJavaAction; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import play.Application; import play.core.j.JavaHandlerComponents; import play.filters.csrf.AddCSRFToken; import play.filters.csrf.CSRF; @@ -24,21 +23,25 @@ import play.libs.crypto.CSRFTokenSigner; import play.mvc.Http; import play.mvc.Result; -import play.test.WithApplication; +import play.test.junit5.ApplicationExtension; -public class JavaCsrf extends WithApplication { +public class JavaCsrf { + + static ApplicationExtension appExtension = new ApplicationExtension(fakeApplication()); + static Application app = appExtension.getApplication(); + static Materializer mat = appExtension.getMaterializer(); private CSRFTokenSigner tokenSigner() { return app.injector().instanceOf(CSRFTokenSigner.class); } @Test - public void getToken() { + void getToken() { String token = tokenSigner().generateSignedToken(); String body = contentAsString( call( - new MockJavaAction(instanceOf(JavaHandlerComponents.class)) { + new MockJavaAction(app.injector().instanceOf(JavaHandlerComponents.class)) { @AddCSRFToken public Result index(Http.Request request) { // #get-token @@ -54,12 +57,12 @@ public Result index(Http.Request request) { } @Test - public void templates() { + void templates() { CSRF.Token token = new CSRF.Token("csrfToken", tokenSigner().generateSignedToken()); String body = contentAsString( call( - new MockJavaAction(instanceOf(JavaHandlerComponents.class)) { + new MockJavaAction(app.injector().instanceOf(JavaHandlerComponents.class)) { @AddCSRFToken public Result index(Http.Request request) { return ok(javaguide.forms.html.csrf.render(request)); @@ -71,24 +74,24 @@ public Result index(Http.Request request) { Matcher matcher = Pattern.compile("action=\"/items\\?csrfToken=[a-f0-9]+-\\d+-([a-f0-9]+)\"").matcher(body); assertTrue(matcher.find()); - assertThat(matcher.group(1), equalTo(tokenSigner().extractSignedToken(token.value()))); + assertEquals(tokenSigner().extractSignedToken(token.value()), matcher.group(1)); matcher = Pattern.compile("value=\"[a-f0-9]+-\\d+-([a-f0-9]+)\"").matcher(body); assertTrue(matcher.find()); - assertThat(matcher.group(1), equalTo(tokenSigner().extractSignedToken(token.value()))); + assertEquals(tokenSigner().extractSignedToken(token.value()), matcher.group(1)); } @Test - public void csrfCheck() { - assertThat( + void csrfCheck() { + assertEquals( + FORBIDDEN, call( - new Controller1(instanceOf(JavaHandlerComponents.class)), + new Controller1(app.injector().instanceOf(JavaHandlerComponents.class)), fakeRequest("POST", "/") .header("Cookie", "foo=bar") .bodyForm(Collections.singletonMap("foo", "bar")), mat) - .status(), - equalTo(FORBIDDEN)); + .status()); } public static class Controller1 extends MockJavaAction { @@ -107,16 +110,15 @@ public Result save() { } @Test - public void csrfAddToken() { - assertThat( + void csrfAddToken() { + assertNotNull( tokenSigner() .extractSignedToken( contentAsString( call( - new Controller2(instanceOf(JavaHandlerComponents.class)), + new Controller2(app.injector().instanceOf(JavaHandlerComponents.class)), fakeRequest("GET", "/"), - mat))), - notNullValue()); + mat)))); } public static class Controller2 extends MockJavaAction { diff --git a/documentation/manual/working/javaGuide/main/forms/code/javaguide/forms/JavaForms.java b/documentation/manual/working/javaGuide/main/forms/code/javaguide/forms/JavaForms.java index d2115b0163e..90d85fa1d39 100644 --- a/documentation/manual/working/javaGuide/main/forms/code/javaguide/forms/JavaForms.java +++ b/documentation/manual/working/javaGuide/main/forms/code/javaguide/forms/JavaForms.java @@ -5,11 +5,11 @@ package javaguide.forms; import static javaguide.testhelpers.MockJavaActionHelper.call; -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import static play.inject.Bindings.bind; import static play.test.Helpers.*; +import akka.stream.Materializer; import com.google.common.collect.ImmutableMap; import com.typesafe.config.Config; import java.time.LocalTime; @@ -21,7 +21,7 @@ import javaguide.forms.u1.User; import javaguide.testhelpers.MockJavaAction; import javax.validation.groups.Default; -import org.junit.Test; +import org.junit.jupiter.api.Test; import play.Application; import play.core.j.JavaHandlerComponents; import play.data.DynamicForm; @@ -41,16 +41,20 @@ import play.libs.typedmap.TypedMap; import play.mvc.*; import play.mvc.Http.MultipartFormData.FilePart; -import play.test.WithApplication; +import play.test.junit5.ApplicationExtension; -public class JavaForms extends WithApplication { +public class JavaForms { + + static ApplicationExtension appExtension = new ApplicationExtension(fakeApplication()); + static Application app = appExtension.getApplication(); + static Materializer mat = appExtension.getMaterializer(); private FormFactory formFactory() { return app.injector().instanceOf(FormFactory.class); } @Test - public void usingForm() { + void usingForm() { FormFactory formFactory = formFactory(); final // sneaky final @@ -72,19 +76,19 @@ public void usingForm() { User user = userForm.bind(lang, attrs, textData, files).get(); // #bind - assertThat(user.getEmail(), equalTo("bob@gmail.com")); - assertThat(user.getPassword(), equalTo("secret")); - assertThat(user.getProfilePicture(), equalTo(myProfilePicture)); + assertEquals("bob@gmail.com", user.getEmail()); + assertEquals("secret", user.getPassword()); + assertEquals(myProfilePicture, user.getProfilePicture()); } @Test - public void bindFromRequest() { + void bindFromRequest() { Result result = call( - new Controller1(instanceOf(JavaHandlerComponents.class)), + new Controller1(app.injector().instanceOf(JavaHandlerComponents.class)), fakeRequest("POST", "/").bodyForm(ImmutableMap.of("email", "e", "password", "p")), mat); - assertThat(contentAsString(result), equalTo("e")); + assertEquals("e", contentAsString(result)); } public class Controller1 extends MockJavaAction { @@ -104,24 +108,23 @@ public Result index(Http.Request request) { } @Test - public void constraints() { + void constraints() { Form userForm = formFactory().form(javaguide.forms.u2.User.class); - assertThat( - userForm.bind(null, TypedMap.empty(), ImmutableMap.of("password", "p")).hasErrors(), - equalTo(true)); + assertTrue(userForm.bind(null, TypedMap.empty(), ImmutableMap.of("password", "p")).hasErrors()); } @Test - public void adhocValidation() { + void adhocValidation() { Result result = call( new U3UserController( - instanceOf(JavaHandlerComponents.class), instanceOf(MessagesApi.class)), + app.injector().instanceOf(JavaHandlerComponents.class), + app.injector().instanceOf(MessagesApi.class)), fakeRequest("POST", "/").bodyForm(ImmutableMap.of("email", "e", "password", "p")), mat); // Run it through the template - assertThat(contentAsString(result), containsString("Invalid email or password")); + assertTrue(contentAsString(result).contains("Invalid email or password")); } public class U3UserController extends MockJavaAction { @@ -152,17 +155,18 @@ public static String authenticate(String email, String password) { } @Test - public void listValidation() { + void listValidation() { Result result = call( new ListValidationController( - instanceOf(JavaHandlerComponents.class), instanceOf(MessagesApi.class)), + app.injector().instanceOf(JavaHandlerComponents.class), + app.injector().instanceOf(MessagesApi.class)), fakeRequest("POST", "/").bodyForm(ImmutableMap.of("email", "e")), mat); // Run it through the template - assertThat(contentAsString(result), containsString("Access denied")); - assertThat(contentAsString(result), containsString("Form could not be submitted")); + assertTrue(contentAsString(result).contains("Access denied")); + assertTrue(contentAsString(result).contains("Form could not be submitted")); } // #list-validate @@ -234,16 +238,17 @@ public Result index(Http.Request request) { } @Test - public void objectValidation() { + void objectValidation() { Result result = call( new ObjectValidationController( - instanceOf(JavaHandlerComponents.class), instanceOf(MessagesApi.class)), + app.injector().instanceOf(JavaHandlerComponents.class), + app.injector().instanceOf(MessagesApi.class)), fakeRequest("POST", "/").bodyForm(ImmutableMap.of("email", "e")), mat); // Run it through the template - assertThat(contentAsString(result), containsString("Invalid credentials")); + assertTrue(contentAsString(result).contains("Invalid credentials")); } // #object-validate @@ -311,13 +316,13 @@ public Result index(Http.Request request) { } @Test - public void handleErrors() { + void handleErrors() { Result result = call( - new Controller2(instanceOf(JavaHandlerComponents.class)), + new Controller2(app.injector().instanceOf(JavaHandlerComponents.class)), fakeRequest("POST", "/").bodyForm(ImmutableMap.of("email", "e")), mat); - assertThat(contentAsString(result), startsWith("Got user")); + assertTrue(contentAsString(result).startsWith("Got user")); } public class Controller2 extends MockJavaAction { @@ -355,7 +360,7 @@ public Result index(Http.Request request) { } @Test - public void fillForm() { + void fillForm() { // User needs a constructor. Give it one. class User extends javaguide.forms.u1.User { User(String email, String password) { @@ -367,18 +372,18 @@ class User extends javaguide.forms.u1.User { // #fill userForm = userForm.fill(new User("bob@gmail.com", "secret")); // #fill - assertThat(userForm.field("email").value().get(), equalTo("bob@gmail.com")); - assertThat(userForm.field("password").value().get(), equalTo("secret")); + assertEquals("bob@gmail.com", userForm.field("email").value().get()); + assertEquals("secret", userForm.field("password").value().get()); } @Test public void dynamicForm() { Result result = call( - new Controller3(instanceOf(JavaHandlerComponents.class)), + new Controller3(app.injector().instanceOf(JavaHandlerComponents.class)), fakeRequest("POST", "/").bodyForm(ImmutableMap.of("firstname", "a", "lastname", "b")), mat); - assertThat(contentAsString(result), equalTo("Hello a b")); + assertEquals("Hello a b", contentAsString(result)); } public class Controller3 extends MockJavaAction { @@ -399,7 +404,7 @@ public Result hello(Http.Request request) { } @Test - public void registerFormatter() { + void registerFormatter() { Application application = new GuiceApplicationBuilder() .overrides(bind(Formatters.class).toProvider(FormattersProvider.class)) @@ -408,8 +413,8 @@ public void registerFormatter() { Form form = application.injector().instanceOf(FormFactory.class).form(WithLocalTime.class); WithLocalTime obj = form.bind(null, TypedMap.empty(), ImmutableMap.of("time", "23:45")).get(); - assertThat(obj.getTime(), equalTo(LocalTime.of(23, 45))); - assertThat(form.fill(obj).field("time").value().get(), equalTo("23:45")); + assertEquals(LocalTime.of(23, 45), obj.getTime()); + assertEquals("23:45", form.fill(obj).field("time").value().get()); } public static class WithLocalTime { @@ -441,16 +446,17 @@ public void validationErrorExamples() { } @Test - public void partialFormSignupValidation() { + void partialFormSignupValidation() { Result result = call( new PartialFormSignupController( - instanceOf(JavaHandlerComponents.class), instanceOf(MessagesApi.class)), + app.injector().instanceOf(JavaHandlerComponents.class), + app.injector().instanceOf(MessagesApi.class)), fakeRequest("POST", "/").bodyForm(ImmutableMap.of()), mat); // Run it through the template - assertThat(contentAsString(result), containsString("This field is required")); + assertTrue(contentAsString(result).contains("This field is required")); } public class PartialFormSignupController extends MockJavaAction { @@ -481,16 +487,17 @@ public Result index(Http.Request request) { } @Test - public void partialFormLoginValidation() { + void partialFormLoginValidation() { Result result = call( new PartialFormLoginController( - instanceOf(JavaHandlerComponents.class), instanceOf(MessagesApi.class)), + app.injector().instanceOf(JavaHandlerComponents.class), + app.injector().instanceOf(MessagesApi.class)), fakeRequest("POST", "/").bodyForm(ImmutableMap.of()), mat); // Run it through the template - assertThat(contentAsString(result), containsString("This field is required")); + assertTrue(contentAsString(result).contains("This field is required")); } public class PartialFormLoginController extends MockJavaAction { @@ -521,16 +528,17 @@ public Result index(Http.Request request) { } @Test - public void partialFormDefaultValidation() { + void partialFormDefaultValidation() { Result result = call( new PartialFormDefaultController( - instanceOf(JavaHandlerComponents.class), instanceOf(MessagesApi.class)), + app.injector().instanceOf(JavaHandlerComponents.class), + app.injector().instanceOf(MessagesApi.class)), fakeRequest("POST", "/").bodyForm(ImmutableMap.of()), mat); // Run it through the template - assertThat(contentAsString(result), containsString("This field is required")); + assertTrue(contentAsString(result).contains("This field is required")); } public class PartialFormDefaultController extends MockJavaAction { @@ -561,16 +569,17 @@ public Result index(Http.Request request) { } @Test - public void partialFormNoGroupValidation() { + void partialFormNoGroupValidation() { Result result = call( new PartialFormNoGroupController( - instanceOf(JavaHandlerComponents.class), instanceOf(MessagesApi.class)), + app.injector().instanceOf(JavaHandlerComponents.class), + app.injector().instanceOf(MessagesApi.class)), fakeRequest("POST", "/").bodyForm(ImmutableMap.of()), mat); // Run it through the template - assertThat(contentAsString(result), containsString("This field is required")); + assertTrue(contentAsString(result).contains("This field is required")); } public class PartialFormNoGroupController extends MockJavaAction { @@ -601,16 +610,17 @@ public Result index(Http.Request request) { } @Test - public void OrderedGroupSequenceValidation() { + void OrderedGroupSequenceValidation() { Result result = call( new OrderedGroupSequenceController( - instanceOf(JavaHandlerComponents.class), instanceOf(MessagesApi.class)), + app.injector().instanceOf(JavaHandlerComponents.class), + app.injector().instanceOf(MessagesApi.class)), fakeRequest("POST", "/").bodyForm(ImmutableMap.of()), mat); // Run it through the template - assertThat(contentAsString(result), containsString("This field is required")); + assertTrue(contentAsString(result).contains("This field is required")); } public class OrderedGroupSequenceController extends MockJavaAction { diff --git a/documentation/manual/working/javaGuide/main/forms/code/javaguide/forms/JavaFormsDirectFieldAccess.java b/documentation/manual/working/javaGuide/main/forms/code/javaguide/forms/JavaFormsDirectFieldAccess.java index 3546760b0fa..60b8b994d89 100644 --- a/documentation/manual/working/javaGuide/main/forms/code/javaguide/forms/JavaFormsDirectFieldAccess.java +++ b/documentation/manual/working/javaGuide/main/forms/code/javaguide/forms/JavaFormsDirectFieldAccess.java @@ -4,28 +4,32 @@ package javaguide.forms; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.junit.Assert.assertThat; +import static org.junit.jupiter.api.Assertions.*; +import static play.test.Helpers.fakeApplication; import java.util.HashMap; import java.util.Locale; import java.util.Map; import javaguide.forms.u4.User; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import play.Application; import play.data.Form; import play.data.FormFactory; import play.i18n.Lang; import play.libs.typedmap.TypedMap; -import play.test.WithApplication; +import play.test.junit5.ApplicationExtension; -public class JavaFormsDirectFieldAccess extends WithApplication { +public class JavaFormsDirectFieldAccess { + + static ApplicationExtension appExtension = new ApplicationExtension(fakeApplication()); + static Application app = appExtension.getApplication(); private FormFactory formFactory() { return app.injector().instanceOf(FormFactory.class); } @Test - public void usingForm() { + void usingForm() { FormFactory formFactory = formFactory(); final // sneaky final @@ -41,7 +45,7 @@ public void usingForm() { User user = userForm.bind(lang, attrs, anyData).get(); - assertThat(user.email, equalTo("bob@gmail.com")); - assertThat(user.password, equalTo("secret")); + assertEquals("bob@gmail.com", user.email); + assertEquals("secret", user.password); } } diff --git a/documentation/manual/working/javaGuide/main/http/code/javaguide/http/JavaActions.java b/documentation/manual/working/javaGuide/main/http/code/javaguide/http/JavaActions.java index fc844c03d26..b90818ed75a 100644 --- a/documentation/manual/working/javaGuide/main/http/code/javaguide/http/JavaActions.java +++ b/documentation/manual/working/javaGuide/main/http/code/javaguide/http/JavaActions.java @@ -5,27 +5,34 @@ package javaguide.http; import static javaguide.testhelpers.MockJavaActionHelper.call; -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import static play.test.Helpers.*; +import akka.stream.Materializer; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import javaguide.testhelpers.MockJavaAction; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import play.Application; import play.core.j.JavaHandlerComponents; import play.mvc.Controller; import play.mvc.Http; import play.mvc.Result; -import play.test.WithApplication; +import play.test.junit5.ApplicationExtension; + +public class JavaActions { + + static ApplicationExtension appExtension = new ApplicationExtension(fakeApplication()); + static Application app = appExtension.getApplication(); + static Materializer mat = appExtension.getMaterializer(); -public class JavaActions extends WithApplication { @Test - public void simpleAction() { - assertThat( + void simpleAction() { + assertEquals( + 200, call( - new MockJavaAction(instanceOf(JavaHandlerComponents.class)) { + new MockJavaAction(app.injector().instanceOf(JavaHandlerComponents.class)) { // #simple-action public Result index(Http.Request request) { return ok("Got request " + request + "!"); @@ -34,30 +41,29 @@ public Result index(Http.Request request) { }, fakeRequest(), mat) - .status(), - equalTo(200)); + .status()); } @Test - public void fullController() { - assertThat( + void fullController() { + assertEquals( + 200, call( - new MockJavaAction(instanceOf(JavaHandlerComponents.class)) { + new MockJavaAction(app.injector().instanceOf(JavaHandlerComponents.class)) { public Result index() { return new javaguide.http.full.Application().index(); } }, fakeRequest(), mat) - .status(), - equalTo(200)); + .status()); } @Test - public void withParams() { + void withParams() { Result result = call( - new MockJavaAction(instanceOf(JavaHandlerComponents.class)) { + new MockJavaAction(app.injector().instanceOf(JavaHandlerComponents.class)) { // #params-action public Result index(String name) { return ok("Hello " + name); @@ -70,15 +76,16 @@ public CompletionStage invocation() { }, fakeRequest(), mat); - assertThat(result.status(), equalTo(200)); - assertThat(contentAsString(result), equalTo("Hello world")); + assertEquals(200, result.status()); + assertEquals("Hello world", contentAsString(result)); } @Test - public void simpleResult() { - assertThat( + void simpleResult() { + assertEquals( + 200, call( - new MockJavaAction(instanceOf(JavaHandlerComponents.class)) { + new MockJavaAction(app.injector().instanceOf(JavaHandlerComponents.class)) { // #simple-result public Result index() { return ok("Hello world!"); @@ -87,12 +94,11 @@ public Result index() { }, fakeRequest(), mat) - .status(), - equalTo(200)); + .status()); } @Test - public void otherResults() { + void otherResults() { class Controller5 extends Controller { void run() { @@ -107,7 +113,7 @@ void run() { Result anyStatus = status(488, "Strange response type"); // #other-results - assertThat(anyStatus.status(), equalTo(488)); + assertEquals(488, anyStatus.status()); } } @@ -126,10 +132,10 @@ static String render(Object o) { } @Test - public void redirectAction() { + void redirectAction() { Result result = call( - new MockJavaAction(instanceOf(JavaHandlerComponents.class)) { + new MockJavaAction(app.injector().instanceOf(JavaHandlerComponents.class)) { // #redirect-action public Result index() { return redirect("/user/home"); @@ -138,15 +144,15 @@ public Result index() { }, fakeRequest(), mat); - assertThat(result.status(), equalTo(SEE_OTHER)); - assertThat(result.header(LOCATION), equalTo(Optional.of("/user/home"))); + assertEquals(SEE_OTHER, result.status()); + assertEquals(Optional.of("/user/home"), result.header(LOCATION)); } @Test - public void temporaryRedirectAction() { + void temporaryRedirectAction() { Result result = call( - new MockJavaAction(instanceOf(JavaHandlerComponents.class)) { + new MockJavaAction(app.injector().instanceOf(JavaHandlerComponents.class)) { // #temporary-redirect-action public Result index() { return temporaryRedirect("/user/home"); @@ -155,7 +161,7 @@ public Result index() { }, fakeRequest(), mat); - assertThat(result.status(), equalTo(TEMPORARY_REDIRECT)); - assertThat(result.header(LOCATION), equalTo(Optional.of("/user/home"))); + assertEquals(TEMPORARY_REDIRECT, result.status()); + assertEquals(Optional.of("/user/home"), result.header(LOCATION)); } } diff --git a/documentation/manual/working/javaGuide/main/http/code/javaguide/http/JavaBodyParsers.java b/documentation/manual/working/javaGuide/main/http/code/javaguide/http/JavaBodyParsers.java index 8a3825c2b7f..ee668c865b4 100644 --- a/documentation/manual/working/javaGuide/main/http/code/javaguide/http/JavaBodyParsers.java +++ b/documentation/manual/working/javaGuide/main/http/code/javaguide/http/JavaBodyParsers.java @@ -5,10 +5,10 @@ package javaguide.http; import static javaguide.testhelpers.MockJavaActionHelper.*; -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import static play.test.Helpers.*; +import akka.stream.Materializer; import akka.stream.javadsl.*; import akka.util.ByteString; import com.fasterxml.jackson.databind.JsonNode; @@ -17,7 +17,8 @@ import java.util.concurrent.Executor; import javaguide.testhelpers.MockJavaAction; import javax.inject.Inject; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import play.Application; import play.core.j.JavaHandlerComponents; import play.http.HttpErrorHandler; import play.libs.F; @@ -27,46 +28,50 @@ import play.libs.ws.WSResponse; import play.mvc.*; import play.mvc.Http.*; -import play.test.WithApplication; +import play.test.junit5.ApplicationExtension; -public class JavaBodyParsers extends WithApplication { +public class JavaBodyParsers { + + static ApplicationExtension appExtension = new ApplicationExtension(fakeApplication()); + static Application app = appExtension.getApplication(); + static Materializer mat = appExtension.getMaterializer(); @Test - public void accessRequestBody() { - assertThat( + void accessRequestBody() { + assertTrue( contentAsString( - call( - new MockJavaAction(instanceOf(JavaHandlerComponents.class)) { - // #access-json-body - public Result index(Http.Request request) { - JsonNode json = request.body().asJson(); - return ok("Got name: " + json.get("name").asText()); - } - // #access-json-body - }, - fakeRequest("POST", "/") - .bodyJson(Json.toJson(Collections.singletonMap("name", "foo"))), - mat)), - containsString("foo")); + call( + new MockJavaAction(app.injector().instanceOf(JavaHandlerComponents.class)) { + // #access-json-body + public Result index(Http.Request request) { + JsonNode json = request.body().asJson(); + return ok("Got name: " + json.get("name").asText()); + } + // #access-json-body + }, + fakeRequest("POST", "/") + .bodyJson(Json.toJson(Collections.singletonMap("name", "foo"))), + mat)) + .contains("foo")); } @Test - public void particularBodyParser() { - assertThat( + void particularBodyParser() { + assertTrue( contentAsString( - call( - new MockJavaAction(instanceOf(JavaHandlerComponents.class)) { - // #particular-body-parser - @BodyParser.Of(BodyParser.Text.class) - public Result index(Http.Request request) { - RequestBody body = request.body(); - return ok("Got text: " + body.asText()); - } - // #particular-body-parser - }, - fakeRequest().bodyText("foo"), - mat)), - containsString("foo")); + call( + new MockJavaAction(app.injector().instanceOf(JavaHandlerComponents.class)) { + // #particular-body-parser + @BodyParser.Of(BodyParser.Text.class) + public Result index(Http.Request request) { + RequestBody body = request.body(); + return ok("Got text: " + body.asText()); + } + // #particular-body-parser + }, + fakeRequest().bodyText("foo"), + mat)) + .contains("foo")); } public abstract static class BodyParserApply implements BodyParser { @@ -78,7 +83,7 @@ public abstract static class BodyParserApply implements BodyParser { // #body-parser-apply } - public static class User { + static class User { public String name; } @@ -120,11 +125,12 @@ public Accumulator> apply(RequestHeader reque } @Test - public void composingBodyParser() { - assertThat( + void composingBodyParser() { + assertEquals( + "Got: foo", contentAsString( call( - new MockJavaAction(instanceOf(JavaHandlerComponents.class)) { + new MockJavaAction(app.injector().instanceOf(JavaHandlerComponents.class)) { // #composing-access @BodyParser.Of(UserBodyParser.class) public Result save(Http.Request request) { @@ -136,24 +142,23 @@ public Result save(Http.Request request) { // #composing-access }, fakeRequest().bodyJson(Json.toJson(Collections.singletonMap("name", "foo"))), - mat)), - equalTo("Got: foo")); + mat))); } @Test - public void maxLength() { + void maxLength() { StringBuilder body = new StringBuilder(); for (int i = 0; i < 1100; i++) { body.append("1234567890"); } - assertThat( + assertEquals( + 413, callWithStringBody( - new MaxLengthAction(instanceOf(JavaHandlerComponents.class)), + new MaxLengthAction(app.injector().instanceOf(JavaHandlerComponents.class)), fakeRequest(), body.toString(), mat) - .status(), - equalTo(413)); + .status()); } public static class MaxLengthAction extends MockJavaAction { @@ -250,11 +255,12 @@ public Accumulator>>> apply( @Test @SuppressWarnings("unchecked") - public void testCsv() { - assertThat( + void testCsv() { + assertEquals( + "Got: foo", contentAsString( call( - new MockJavaAction(instanceOf(JavaHandlerComponents.class)) { + new MockJavaAction(app.injector().instanceOf(JavaHandlerComponents.class)) { @BodyParser.Of(CsvBodyParser.class) public Result uploadCsv(Http.Request request) { String value = @@ -263,7 +269,6 @@ public Result uploadCsv(Http.Request request) { } }, fakeRequest().bodyText("1,2\n3,4,foo\n5,6"), - mat)), - equalTo("Got: foo")); + mat))); } } diff --git a/documentation/manual/working/javaGuide/main/http/code/javaguide/http/JavaContentNegotiation.java b/documentation/manual/working/javaGuide/main/http/code/javaguide/http/JavaContentNegotiation.java index 2d8bf4cd984..f35c04a1af0 100644 --- a/documentation/manual/working/javaGuide/main/http/code/javaguide/http/JavaContentNegotiation.java +++ b/documentation/manual/working/javaGuide/main/http/code/javaguide/http/JavaContentNegotiation.java @@ -5,27 +5,33 @@ package javaguide.http; import static javaguide.testhelpers.MockJavaActionHelper.*; -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import static play.test.Helpers.*; +import akka.stream.Materializer; import java.util.Collections; import java.util.List; import javaguide.testhelpers.MockJavaAction; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import play.Application; import play.core.j.JavaHandlerComponents; import play.libs.Json; import play.mvc.*; -import play.test.WithApplication; +import play.test.junit5.ApplicationExtension; -public class JavaContentNegotiation extends WithApplication { +public class JavaContentNegotiation { + + static ApplicationExtension appExtension = new ApplicationExtension(fakeApplication()); + static Application app = appExtension.getApplication(); + static Materializer mat = appExtension.getMaterializer(); @Test - public void negotiateContent() { - assertThat( + void negotiateContent() { + assertEquals( + "html list of items", contentAsString( call( - new MockJavaAction(instanceOf(JavaHandlerComponents.class)) { + new MockJavaAction(app.injector().instanceOf(JavaHandlerComponents.class)) { // #negotiate-content public Result list(Http.Request request) { List items = Item.find.all(); @@ -38,8 +44,7 @@ public Result list(Http.Request request) { // #negotiate-content }, fakeRequest().header("Accept", "text/html"), - mat)), - equalTo("html list of items")); + mat))); } public static class Item { diff --git a/documentation/manual/working/javaGuide/main/http/code/javaguide/http/JavaResponse.java b/documentation/manual/working/javaGuide/main/http/code/javaguide/http/JavaResponse.java index 0c7aaffd286..5aa8784902e 100644 --- a/documentation/manual/working/javaGuide/main/http/code/javaguide/http/JavaResponse.java +++ b/documentation/manual/working/javaGuide/main/http/code/javaguide/http/JavaResponse.java @@ -5,14 +5,13 @@ package javaguide.http; import static javaguide.testhelpers.MockJavaActionHelper.*; -import static org.hamcrest.CoreMatchers.containsString; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; import static play.mvc.Controller.*; +import static play.test.Helpers.fakeApplication; import static play.test.Helpers.fakeRequest; import akka.NotUsed; +import akka.stream.Materializer; import akka.stream.javadsl.Source; import akka.util.ByteString; import com.fasterxml.jackson.databind.JsonNode; @@ -24,7 +23,8 @@ import java.util.Optional; import java.util.stream.Collectors; import javaguide.testhelpers.MockJavaAction; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import play.Application; import play.core.j.JavaHandlerComponents; import play.libs.Json; import play.mvc.Http; @@ -33,53 +33,57 @@ import play.mvc.RangeResults; import play.mvc.Result; import play.test.Helpers; -import play.test.WithApplication; +import play.test.junit5.ApplicationExtension; -public class JavaResponse extends WithApplication { +public class JavaResponse { + + static ApplicationExtension appExtension = new ApplicationExtension(fakeApplication()); + static Application app = appExtension.getApplication(); + static Materializer mat = appExtension.getMaterializer(); @Test - public void textContentType() { + void textContentType() { // #text-content-type Result textResult = ok("Hello World!"); // #text-content-type - assertThat(textResult.contentType().get(), containsString("text/plain")); + assertTrue(textResult.contentType().get().contains("text/plain")); } @Test - public void jsonContentType() { + void jsonContentType() { String object = ""; // #json-content-type JsonNode json = Json.toJson(object); Result jsonResult = ok(json); // #json-content-type - assertThat(jsonResult.contentType().get(), containsString("application/json")); + assertTrue(jsonResult.contentType().get().contains("application/json")); } @Test - public void customContentType() { + void customContentType() { // #custom-content-type Result htmlResult = ok("

Hello World!

").as("text/html"); // #custom-content-type - assertThat(htmlResult.contentType().get(), containsString("text/html")); + assertTrue(htmlResult.contentType().get().contains("text/html")); } @Test - public void customDefiningContentType() { + void customDefiningContentType() { // #content-type_defined_html Result htmlResult = ok("

Hello World!

").as(MimeTypes.HTML); // #content-type_defined_html - assertThat(htmlResult.contentType().get(), containsString("text/html")); + assertTrue(htmlResult.contentType().get().contains("text/html")); } @Test - public void responseHeaders() { + void responseHeaders() { Map headers = call( - new MockJavaAction(instanceOf(JavaHandlerComponents.class)) { + new MockJavaAction(app.injector().instanceOf(JavaHandlerComponents.class)) { // #response-headers public Result index() { return ok("

Hello World!

") @@ -92,15 +96,15 @@ public Result index() { fakeRequest(), mat) .headers(); - assertThat(headers.get(CACHE_CONTROL), equalTo("max-age=3600")); - assertThat(headers.get(ETAG), equalTo("some-etag-calculated-value")); + assertEquals("max-age=3600", headers.get(CACHE_CONTROL)); + assertEquals("some-etag-calculated-value", headers.get(ETAG)); } @Test - public void setCookie() { + void setCookie() { Http.Cookies cookies = call( - new MockJavaAction(instanceOf(JavaHandlerComponents.class)) { + new MockJavaAction(app.injector().instanceOf(JavaHandlerComponents.class)) { // #set-cookie public Result index() { return ok("

Hello World!

") @@ -115,14 +119,14 @@ public Result index() { Optional cookie = cookies.get("theme"); assertTrue(cookie.isPresent()); - assertThat(cookie.get().value(), equalTo("blue")); + assertEquals("blue", cookie.get().value()); } @Test - public void detailedSetCookie() { + void detailedSetCookie() { Http.Cookies cookies = call( - new MockJavaAction(instanceOf(JavaHandlerComponents.class)) { + new MockJavaAction(app.injector().instanceOf(JavaHandlerComponents.class)) { // #detailed-set-cookie public Result index() { return ok("

Hello World!

") @@ -147,21 +151,21 @@ public Result index() { assertTrue(cookieOpt.isPresent()); Cookie cookie = cookieOpt.get(); - assertThat(cookie.name(), equalTo("theme")); - assertThat(cookie.value(), equalTo("blue")); - assertThat(cookie.maxAge(), equalTo(3600)); - assertThat(cookie.path(), equalTo("/some/path")); - assertThat(cookie.domain(), equalTo(".example.com")); - assertThat(cookie.secure(), equalTo(false)); - assertThat(cookie.httpOnly(), equalTo(true)); - assertThat(cookie.sameSite(), equalTo(Optional.of(Cookie.SameSite.STRICT))); + assertEquals("theme", cookie.name()); + assertEquals("blue", cookie.value()); + assertEquals(3600, cookie.maxAge()); + assertEquals("/some/path", cookie.path()); + assertEquals(".example.com", cookie.domain()); + assertEquals(false, cookie.secure()); + assertEquals(true, cookie.httpOnly()); + assertEquals(Optional.of(Cookie.SameSite.STRICT), cookie.sameSite()); } @Test - public void discardCookie() { + void discardCookie() { Http.Cookies cookies = call( - new MockJavaAction(instanceOf(JavaHandlerComponents.class)) { + new MockJavaAction(app.injector().instanceOf(JavaHandlerComponents.class)) { // #discard-cookie public Result index() { return ok("

Hello World!

").as(MimeTypes.HTML).discardingCookie("theme"); @@ -173,15 +177,16 @@ public Result index() { .cookies(); Optional cookie = cookies.get("theme"); assertTrue(cookie.isPresent()); - assertThat(cookie.get().name(), equalTo("theme")); - assertThat(cookie.get().value(), equalTo("")); + assertEquals("theme", cookie.get().name()); + assertEquals("", cookie.get().value()); } @Test - public void charset() { - assertThat( + void charset() { + assertEquals( + "iso-8859-1", call( - new MockJavaAction(instanceOf(JavaHandlerComponents.class)) { + new MockJavaAction(app.injector().instanceOf(JavaHandlerComponents.class)) { // #charset public Result index() { return ok("

Hello World!

", "iso-8859-1") @@ -192,15 +197,14 @@ public Result index() { fakeRequest(), mat) .charset() - .get(), - equalTo("iso-8859-1")); + .get()); } @Test - public void rangeResultInputStream() { + void rangeResultInputStream() { Result result = call( - new MockJavaAction(instanceOf(JavaHandlerComponents.class)) { + new MockJavaAction(app.injector().instanceOf(JavaHandlerComponents.class)) { // #range-result-input-stream public Result index(Http.Request request) { String content = "This is the full content!"; @@ -216,15 +220,15 @@ private InputStream getInputStream(String content) { fakeRequest().header(RANGE, "bytes=0-3"), mat); - assertThat(result.status(), equalTo(PARTIAL_CONTENT)); - assertThat(Helpers.contentAsString(result, mat), equalTo("This")); + assertEquals(PARTIAL_CONTENT, result.status()); + assertEquals("This", Helpers.contentAsString(result, mat)); } @Test - public void rangeResultSource() { + void rangeResultSource() { Result result = call( - new MockJavaAction(instanceOf(JavaHandlerComponents.class)) { + new MockJavaAction(app.injector().instanceOf(JavaHandlerComponents.class)) { // #range-result-source public Result index(Http.Request request) { String content = "This is the full content!"; @@ -247,15 +251,15 @@ private Source sourceFrom(String content) { fakeRequest().header(RANGE, "bytes=0-3"), mat); - assertThat(result.status(), equalTo(PARTIAL_CONTENT)); - assertThat(Helpers.contentAsString(result, mat), equalTo("This")); + assertEquals(PARTIAL_CONTENT, result.status()); + assertEquals("This", Helpers.contentAsString(result, mat)); } @Test - public void rangeResultSourceOffset() { + void rangeResultSourceOffset() { Result result = call( - new MockJavaAction(instanceOf(JavaHandlerComponents.class)) { + new MockJavaAction(app.injector().instanceOf(JavaHandlerComponents.class)) { // #range-result-source-with-offset public Result index(Http.Request request) { String content = "This is the full content!"; @@ -282,7 +286,7 @@ private Source sourceFrom(String content) { fakeRequest().header(RANGE, "bytes=8-10"), mat); - assertThat(result.status(), equalTo(PARTIAL_CONTENT)); - assertThat(Helpers.contentAsString(result, mat), equalTo("the")); + assertEquals(PARTIAL_CONTENT, result.status()); + assertEquals("the", Helpers.contentAsString(result, mat)); } } diff --git a/documentation/manual/working/javaGuide/main/http/code/javaguide/http/JavaSessionFlash.java b/documentation/manual/working/javaGuide/main/http/code/javaguide/http/JavaSessionFlash.java index 5879ebeef44..b49f17f0c43 100644 --- a/documentation/manual/working/javaGuide/main/http/code/javaguide/http/JavaSessionFlash.java +++ b/documentation/manual/working/javaGuide/main/http/code/javaguide/http/JavaSessionFlash.java @@ -4,10 +4,13 @@ package javaguide.http; -import org.junit.*; +import akka.stream.Materializer; +import org.junit.jupiter.api.*; import play.core.j.JavaHandlerComponents; -import play.test.WithApplication; import javaguide.testhelpers.MockJavaAction; +import play.Application; +import play.test.junit5.ApplicationExtension; + // #imports import play.mvc.*; @@ -15,18 +18,20 @@ // #imports import static javaguide.testhelpers.MockJavaActionHelper.*; -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import static play.test.Helpers.*; -public class JavaSessionFlash extends WithApplication { - +public class JavaSessionFlash { + static ApplicationExtension appExtension = new ApplicationExtension(fakeApplication()); + static Application app = appExtension.getApplication(); + static Materializer mat = appExtension.getMaterializer(); @Test - public void readSession() { - assertThat( + void readSession() { + assertEquals( + "Hello foo", contentAsString( call( - new MockJavaAction(instanceOf(JavaHandlerComponents.class)) { + new MockJavaAction(app.injector().instanceOf(JavaHandlerComponents.class)) { // #read-session public Result index(Http.Request request) { return request @@ -38,15 +43,14 @@ public Result index(Http.Request request) { // #read-session }, fakeRequest().session("connected", "foo"), - mat)), - equalTo("Hello foo")); + mat))); } @Test - public void storeSession() { + void storeSession() { Session session = call( - new MockJavaAction(instanceOf(JavaHandlerComponents.class)) { + new MockJavaAction(app.injector().instanceOf(JavaHandlerComponents.class)) { // #store-session public Result login(Http.Request request) { return redirect("/home") @@ -57,14 +61,14 @@ public Result login(Http.Request request) { fakeRequest(), mat) .session(); - assertThat(session.get("connected").get(), equalTo("user@gmail.com")); + assertEquals("user@gmail.com", session.get("connected").get()); } @Test - public void removeFromSession() { + void removeFromSession() { Session session = call( - new MockJavaAction(instanceOf(JavaHandlerComponents.class)) { + new MockJavaAction(app.injector().instanceOf(JavaHandlerComponents.class)) { // #remove-from-session public Result logout(Http.Request request) { return redirect("/home").removingFromSession(request, "connected"); @@ -78,10 +82,10 @@ public Result logout(Http.Request request) { } @Test - public void discardWholeSession() { + void discardWholeSession() { Session session = call( - new MockJavaAction(instanceOf(JavaHandlerComponents.class)) { + new MockJavaAction(app.injector().instanceOf(JavaHandlerComponents.class)) { // #discard-whole-session public Result logout() { return redirect("/home").withNewSession(); @@ -95,11 +99,12 @@ public Result logout() { } @Test - public void readFlash() { - assertThat( + void readFlash() { + assertEquals( + "hi", contentAsString( call( - new MockJavaAction(instanceOf(JavaHandlerComponents.class)) { + new MockJavaAction(app.injector().instanceOf(JavaHandlerComponents.class)) { // #read-flash public Result index(Http.Request request) { return ok(request.flash().get("success").orElse("Welcome!")); @@ -107,15 +112,14 @@ public Result index(Http.Request request) { // #read-flash }, fakeRequest().flash("success", "hi"), - mat)), - equalTo("hi")); + mat))); } @Test - public void storeFlash() { + void storeFlash() { Flash flash = call( - new MockJavaAction(instanceOf(JavaHandlerComponents.class)) { + new MockJavaAction(app.injector().instanceOf(JavaHandlerComponents.class)) { // #store-flash public Result save() { return redirect("/home").flashing("success", "The item has been created"); @@ -125,20 +129,18 @@ public Result save() { fakeRequest(), mat) .flash(); - assertThat(flash.get("success").get(), equalTo("The item has been created")); + assertEquals("The item has been created", flash.get("success").get()); } @Test - public void accessFlashInTemplate() { + void accessFlashInTemplate() { MockJavaAction index = - new MockJavaAction(instanceOf(JavaHandlerComponents.class)) { + new MockJavaAction(app.injector().instanceOf(JavaHandlerComponents.class)) { public Result index(Http.Request request) { return ok(javaguide.http.views.html.index.render(request.flash())); } }; - assertThat(contentAsString(call(index, fakeRequest(), mat)).trim(), equalTo("Welcome!")); - assertThat( - contentAsString(call(index, fakeRequest().flash("success", "Flashed!"), mat)).trim(), - equalTo("Flashed!")); + assertEquals("Welcome!", contentAsString(call(index, fakeRequest(), mat)).trim()); + assertEquals("Flashed!", contentAsString(call(index, fakeRequest().flash("success", "Flashed!"), mat)).trim()); } } diff --git a/documentation/manual/working/javaGuide/main/i18n/code/javaguide/i18n/JavaI18N.java b/documentation/manual/working/javaGuide/main/i18n/code/javaguide/i18n/JavaI18N.java index 322a6f66b8d..b484000cbf8 100644 --- a/documentation/manual/working/javaGuide/main/i18n/code/javaguide/i18n/JavaI18N.java +++ b/documentation/manual/working/javaGuide/main/i18n/code/javaguide/i18n/JavaI18N.java @@ -5,10 +5,10 @@ package javaguide.i18n; import static java.util.stream.Collectors.joining; -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import static play.test.Helpers.*; +import akka.stream.Materializer; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import java.util.*; @@ -16,7 +16,7 @@ import javaguide.i18n.html.hellotemplateshort; import javaguide.testhelpers.MockJavaAction; import javaguide.testhelpers.MockJavaActionHelper; -import org.junit.Test; +import org.junit.jupiter.api.Test; import play.Application; import play.core.j.JavaHandlerComponents; import play.i18n.Lang; @@ -24,39 +24,40 @@ import play.i18n.MessagesApi; import play.mvc.Http; import play.mvc.Result; -import play.test.WithApplication; - -public class JavaI18N extends WithApplication { - - @Override - public Application provideApplication() { - return fakeApplication( - ImmutableMap.of( - "play.i18n.langs", - ImmutableList.of("en", "en-US", "fr"), - "messages.path", - "javaguide/i18n")); - } +import play.test.junit5.ApplicationExtension; + +public class JavaI18N { + static ApplicationExtension appExtension = + new ApplicationExtension( + fakeApplication( + ImmutableMap.of( + "play.i18n.langs", + ImmutableList.of("en", "en-US", "fr"), + "messages.path", + "javaguide/i18n"))); + static Application app = appExtension.getApplication(); + static Materializer mat = appExtension.getMaterializer(); @Test - public void checkSpecifyLangHello() { - MessagesApi messagesApi = instanceOf(MessagesApi.class); + void checkSpecifyLangHello() { + MessagesApi messagesApi = app.injector().instanceOf(MessagesApi.class); // #specify-lang-render String title = messagesApi.get(Lang.forCode("fr"), "hello"); // #specify-lang-render - assertTrue(title.equals("bonjour")); + assertEquals("bonjour", title); } @Test - public void checkDefaultHello() { + void checkDefaultHello() { Result result = MockJavaActionHelper.call( new DefaultLangController( - instanceOf(JavaHandlerComponents.class), instanceOf(MessagesApi.class)), + app.injector().instanceOf(JavaHandlerComponents.class), + app.injector().instanceOf(MessagesApi.class)), fakeRequest("GET", "/"), mat); - assertThat(contentAsString(result), containsString("hello")); + assertTrue(contentAsString(result).contains("hello")); } public static class DefaultLangController extends MockJavaAction { @@ -77,14 +78,15 @@ public Result index(Http.Request request) { } @Test - public void checkDefaultScalaHello() { + void checkDefaultScalaHello() { Result result = MockJavaActionHelper.call( new DefaultScalaLangController( - instanceOf(JavaHandlerComponents.class), instanceOf(MessagesApi.class)), + app.injector().instanceOf(JavaHandlerComponents.class), + app.injector().instanceOf(MessagesApi.class)), fakeRequest("GET", "/"), mat); - assertThat(contentAsString(result), containsString("hello")); + assertTrue(contentAsString(result).contains("hello")); } public static class DefaultScalaLangController extends MockJavaAction { @@ -104,21 +106,22 @@ public Result index(Http.Request request) { } @Test - public void checkChangeLangHello() { + void checkChangeLangHello() { Result result = MockJavaActionHelper.call( new ChangeLangController( - instanceOf(JavaHandlerComponents.class), instanceOf(MessagesApi.class)), + app.injector().instanceOf(JavaHandlerComponents.class), + app.injector().instanceOf(MessagesApi.class)), fakeRequest("GET", "/"), mat); - assertThat(contentAsString(result), containsString("bonjour")); + assertTrue(contentAsString(result).contains("bonjour")); } @Test - public void checkRequestMessages() { + void checkRequestMessages() { RequestMessagesController c = app.injector().instanceOf(RequestMessagesController.class); Result result = MockJavaActionHelper.call(c, fakeRequest("GET", "/"), mat); - assertThat(contentAsString(result), containsString("hello")); + assertTrue(contentAsString(result).contains("hello")); } public static class ChangeLangController extends MockJavaAction { @@ -158,14 +161,15 @@ public Result index(Http.Request request) { } @Test - public void checkSetTransientLangHello() { + void checkSetTransientLangHello() { Result result = MockJavaActionHelper.call( new SetTransientLangController( - instanceOf(JavaHandlerComponents.class), instanceOf(MessagesApi.class)), + app.injector().instanceOf(JavaHandlerComponents.class), + app.injector().instanceOf(MessagesApi.class)), fakeRequest("GET", "/"), mat); - assertThat(contentAsString(result), containsString("howdy")); + assertTrue(contentAsString(result).contains("howdy")); } public static class SetTransientLangController extends MockJavaAction { @@ -188,14 +192,14 @@ public Result index(Http.Request request) { } @Test - public void testAcceptedLanguages() { + void testAcceptedLanguages() { Result result = MockJavaActionHelper.call( - new AcceptedLanguageController(instanceOf(JavaHandlerComponents.class)), + new AcceptedLanguageController(app.injector().instanceOf(JavaHandlerComponents.class)), fakeRequest("GET", "/") .header("Accept-Language", "fr-CH, fr;q=0.9, en;q=0.8, de;q=0.7, *;q=0.5"), mat); - assertThat(contentAsString(result), equalTo("fr-CH,fr,en,de")); + assertEquals("fr-CH,fr,en,de", contentAsString(result)); } private static final class AcceptedLanguageController extends MockJavaAction { @@ -213,7 +217,7 @@ public Result index(Http.Request request) { } @Test - public void testSingleApostrophe() { + void testSingleApostrophe() { assertTrue(singleApostrophe()); } @@ -230,7 +234,7 @@ private Boolean singleApostrophe() { } @Test - public void testEscapedParameters() { + void testEscapedParameters() { assertTrue(escapedParameters()); } @@ -259,9 +263,9 @@ private MessagesApi explicitMessagesApi() { // #explicit-messages-api @Test - public void testExplicitMessagesApi() { + void testExplicitMessagesApi() { MessagesApi messagesApi = explicitMessagesApi(); String message = messagesApi.get(Lang.defaultLang(), "foo"); - assertThat(message, equalTo("bar")); + assertEquals("bar", message); } } diff --git a/documentation/manual/working/javaGuide/main/json/code/javaguide/json/JavaJsonActions.java b/documentation/manual/working/javaGuide/main/json/code/javaguide/json/JavaJsonActions.java index 094dff7ded6..dcb1ed1c9c6 100644 --- a/documentation/manual/working/javaGuide/main/json/code/javaguide/json/JavaJsonActions.java +++ b/documentation/manual/working/javaGuide/main/json/code/javaguide/json/JavaJsonActions.java @@ -5,25 +5,30 @@ package javaguide.json; import static javaguide.testhelpers.MockJavaActionHelper.call; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import static play.test.Helpers.*; +import akka.stream.Materializer; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ObjectNode; import java.util.ArrayList; import java.util.List; import java.util.Optional; import javaguide.testhelpers.MockJavaAction; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import play.Application; import play.core.j.JavaHandlerComponents; import play.libs.Json; import play.mvc.BodyParser; import play.mvc.Http; import play.mvc.Result; -import play.test.WithApplication; +import play.test.junit5.ApplicationExtension; -public class JavaJsonActions extends WithApplication { +public class JavaJsonActions { + + static ApplicationExtension appExtension = new ApplicationExtension(fakeApplication()); + static Application app = appExtension.getApplication(); + static Materializer mat = appExtension.getMaterializer(); // #person-class // Note: can use getters/setters as well; here we just use public fields directly. @@ -36,20 +41,20 @@ public static class Person { // #person-class @Test - public void fromJson() { + void fromJson() { // #from-json // parse the JSON as a JsonNode JsonNode json = Json.parse("{\"firstName\":\"Foo\", \"lastName\":\"Bar\", \"age\":13}"); // read the JsonNode as a Person Person person = Json.fromJson(json, Person.class); // #from-json - assertThat(person.firstName, equalTo("Foo")); - assertThat(person.lastName, equalTo("Bar")); - assertThat(person.age, equalTo(13)); + assertEquals("Foo", person.firstName); + assertEquals("Bar", person.lastName); + assertEquals(13, person.age); } @Test - public void toJson() { + void toJson() { // #to-json Person person = new Person(); person.firstName = "Foo"; @@ -57,53 +62,54 @@ public void toJson() { person.age = 30; JsonNode personJson = Json.toJson(person); // {"firstName": "Foo", "lastName": "Bar", "age": 30} // #to-json - assertThat(personJson.get("firstName").asText(), equalTo("Foo")); - assertThat(personJson.get("lastName").asText(), equalTo("Bar")); - assertThat(personJson.get("age").asInt(), equalTo(30)); + assertEquals("Foo", personJson.get("firstName").asText()); + assertEquals("Bar", personJson.get("lastName").asText()); + assertEquals(30, personJson.get("age").asInt()); } @Test - public void requestAsAnyContentAction() { - assertThat( + void requestAsAnyContentAction() { + assertEquals( + "Hello Greg", contentAsString( call( - new JsonRequestAsAnyContentAction(instanceOf(JavaHandlerComponents.class)), + new JsonRequestAsAnyContentAction( + app.injector().instanceOf(JavaHandlerComponents.class)), fakeRequest().bodyJson(Json.parse("{\"name\":\"Greg\"}")), - mat)), - equalTo("Hello Greg")); + mat))); } @Test - public void requestAsJsonAction() { - assertThat( + void requestAsJsonAction() { + assertEquals( + "Hello Greg", contentAsString( call( - new JsonRequestAsJsonAction(instanceOf(JavaHandlerComponents.class)), + new JsonRequestAsJsonAction(app.injector().instanceOf(JavaHandlerComponents.class)), fakeRequest().bodyJson(Json.parse("{\"name\":\"Greg\"}")), - mat)), - equalTo("Hello Greg")); + mat))); } @Test - public void responseAction() { - assertThat( + void responseAction() { + assertEquals( + "{\"exampleField1\":\"foobar\",\"exampleField2\":\"Hello world!\"}", contentAsString( call( - new JsonResponseAction(instanceOf(JavaHandlerComponents.class)), + new JsonResponseAction(app.injector().instanceOf(JavaHandlerComponents.class)), fakeRequest(), - mat)), - equalTo("{\"exampleField1\":\"foobar\",\"exampleField2\":\"Hello world!\"}")); + mat))); } @Test - public void responseDaoAction() { - assertThat( + void responseDaoAction() { + assertEquals( + "[{\"firstName\":\"Foo\",\"lastName\":\"Bar\",\"age\":30}]", contentAsString( call( - new JsonResponseDaoAction(instanceOf(JavaHandlerComponents.class)), + new JsonResponseDaoAction(app.injector().instanceOf(JavaHandlerComponents.class)), fakeRequest(), - mat)), - equalTo("[{\"firstName\":\"Foo\",\"lastName\":\"Bar\",\"age\":30}]")); + mat))); } static class JsonRequestAsAnyContentAction extends MockJavaAction { diff --git a/documentation/manual/working/javaGuide/main/logging/code/javaguide/logging/JavaLogging.java b/documentation/manual/working/javaGuide/main/logging/code/javaguide/logging/JavaLogging.java index 7cd83a753b8..b8e6d8d2d4b 100644 --- a/documentation/manual/working/javaGuide/main/logging/code/javaguide/logging/JavaLogging.java +++ b/documentation/manual/working/javaGuide/main/logging/code/javaguide/logging/JavaLogging.java @@ -6,9 +6,8 @@ import java.util.Random; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.junit.Assert.assertThat; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; // #logging-import import org.slf4j.Logger; @@ -39,19 +38,19 @@ public void testDefaultLogger() { } @Test - public void testCreateLogger() { + void testCreateLogger() { // #logging-create-logger-name final Logger accessLogger = LoggerFactory.getLogger("access"); // #logging-create-logger-name - assertThat(accessLogger.getName(), equalTo("access")); + assertEquals("access", accessLogger.getName()); // #logging-create-logger-class final Logger log = LoggerFactory.getLogger(this.getClass()); // #logging-create-logger-class - assertThat(log.getName(), equalTo("javaguide.logging.JavaLogging")); + assertEquals("javaguide.logging.JavaLogging", log.getName()); } private int riskyCalculation() { diff --git a/documentation/manual/working/javaGuide/main/tests/JavaTestingWithDatabases.md b/documentation/manual/working/javaGuide/main/tests/JavaTestingWithDatabases.md index 239d00aa65a..d679be8bf97 100644 --- a/documentation/manual/working/javaGuide/main/tests/JavaTestingWithDatabases.md +++ b/documentation/manual/working/javaGuide/main/tests/JavaTestingWithDatabases.md @@ -10,7 +10,7 @@ Play provides a number of utilities for helping to test database access code tha To test with a database backend, you only need: -@[content](code/javaguide.tests.databases.sbt) +@[content](code/javaguide.test.junit5.databases.sbt) To connect to a database, at a minimum, you just need database driver name and the url of the database, using the [`Database`](api/java/play/db/Database.html) static factory methods. For example, to connect to MySQL, you might use the following: diff --git a/documentation/manual/working/javaGuide/main/tests/code/javaguide.tests.routes b/documentation/manual/working/javaGuide/main/tests/code/javaguide.test.junit4.routes similarity index 100% rename from documentation/manual/working/javaGuide/main/tests/code/javaguide.tests.routes rename to documentation/manual/working/javaGuide/main/tests/code/javaguide.test.junit4.routes diff --git a/documentation/manual/working/javaGuide/main/tests/code/javaguide.tests.databases.sbt b/documentation/manual/working/javaGuide/main/tests/code/javaguide.test.junit5.databases.sbt similarity index 100% rename from documentation/manual/working/javaGuide/main/tests/code/javaguide.tests.databases.sbt rename to documentation/manual/working/javaGuide/main/tests/code/javaguide.test.junit5.databases.sbt diff --git a/documentation/manual/working/javaGuide/main/tests/code/javaguide.tests.guice.routes b/documentation/manual/working/javaGuide/main/tests/code/javaguide.test.junit5.guice.routes similarity index 100% rename from documentation/manual/working/javaGuide/main/tests/code/javaguide.tests.guice.routes rename to documentation/manual/working/javaGuide/main/tests/code/javaguide.test.junit5.guice.routes diff --git a/documentation/manual/working/javaGuide/main/tests/code/javaguide.test.junit5.routes b/documentation/manual/working/javaGuide/main/tests/code/javaguide.test.junit5.routes new file mode 100644 index 00000000000..080c01f7d2f --- /dev/null +++ b/documentation/manual/working/javaGuide/main/tests/code/javaguide.test.junit5.routes @@ -0,0 +1,4 @@ +# Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. + +GET / controllers.HomeController.index() +POST / controllers.HomeController.post(request: Request) \ No newline at end of file diff --git a/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/controllers/HomeController.java b/documentation/manual/working/javaGuide/main/tests/code/javaguide/controllers/HomeController.java similarity index 84% rename from documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/controllers/HomeController.java rename to documentation/manual/working/javaGuide/main/tests/code/javaguide/controllers/HomeController.java index 419b10fae6f..b27502bbc0a 100644 --- a/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/controllers/HomeController.java +++ b/documentation/manual/working/javaGuide/main/tests/code/javaguide/controllers/HomeController.java @@ -9,7 +9,7 @@ public class HomeController extends Controller { public Result index() { - return ok(javaguide.tests.html.index.render("Welcome to Play!")); + return ok(javaguide.test.junit5.html.index.render("Welcome to Play!")); } public Result post(Http.Request request) { diff --git a/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit4/BrowserFunctionalTest.java b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit4/BrowserFunctionalTest.java index 18bd339c167..6efa885db01 100644 --- a/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit4/BrowserFunctionalTest.java +++ b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit4/BrowserFunctionalTest.java @@ -2,12 +2,13 @@ * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. */ -package javaguide.tests; +package javaguide.test.junit4; import static org.junit.Assert.*; import org.junit.*; import play.test.*; +import play.test.junit4.*; // #test-withbrowser public class BrowserFunctionalTest extends WithBrowser { diff --git a/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit4/FunctionalTest.java b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit4/FunctionalTest.java index 67de9a73eef..ec717b25404 100644 --- a/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit4/FunctionalTest.java +++ b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit4/FunctionalTest.java @@ -12,6 +12,7 @@ import play.mvc.*; import play.test.*; +import play.test.junit4.*; import play.libs.ws.*; import static play.test.Helpers.*; @@ -21,7 +22,7 @@ import play.mvc.Http.RequestBuilder; // #bad-route-import -import javaguide.tests.controllers.routes; +import javaguide.test.junit4.controllers.routes; // #test-withapp public class FunctionalTest extends WithApplication { @@ -52,13 +53,13 @@ public void testGoodRouteCall() { private TestServer testServer() { Map config = new HashMap(); - config.put("play.http.router", "javaguide.tests.Routes"); + config.put("play.http.router", "javaguide.test.junit4.Routes"); return Helpers.testServer(fakeApplication(config)); } private TestServer testServer(int port) { Map config = new HashMap(); - config.put("play.http.router", "javaguide.tests.Routes"); + config.put("play.http.router", "javaguide.test.junit4.Routes"); return Helpers.testServer(port, fakeApplication(config)); } diff --git a/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit4/ServerFunctionalTest.java b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit4/ServerFunctionalTest.java index b88e9ebe00d..e2c0be1d49e 100644 --- a/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit4/ServerFunctionalTest.java +++ b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit4/ServerFunctionalTest.java @@ -12,6 +12,7 @@ import org.junit.*; import play.libs.ws.*; import play.test.*; +import play.test.junit4.*; // #test-withserver public class ServerFunctionalTest extends WithServer { diff --git a/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit4/controllers/HomeController.java b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit4/controllers/HomeController.java new file mode 100644 index 00000000000..5af9b19225c --- /dev/null +++ b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit4/controllers/HomeController.java @@ -0,0 +1,18 @@ +/* + * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. + */ + +package javaguide.test.junit4.controllers; + +import play.mvc.*; + +public class HomeController extends Controller { + + public Result index() { + return ok(javaguide.test.junit4.html.index.render("Welcome to Play!")); + } + + public Result post(Http.Request request) { + return redirect(routes.HomeController.index()); + } +} diff --git a/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit4/index.scala.html b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit4/index.scala.html new file mode 100644 index 00000000000..b73b280cf40 --- /dev/null +++ b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit4/index.scala.html @@ -0,0 +1,4 @@ +@(title: String) + +

@title

+
click me diff --git a/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/ControllerTest.java b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/ControllerTest.java index 981aac023cf..fdec6ed8744 100644 --- a/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/ControllerTest.java +++ b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/ControllerTest.java @@ -16,7 +16,6 @@ import play.twirl.api.Content; class ControllerTest { - @Test void testIndex() { Result result = new HomeController().index(); @@ -33,7 +32,7 @@ void testIndex() { @Test void renderTemplate() { // ###replace: Content html = views.html.index.render("Welcome to Play!"); - Content html = javaguide.tests.html.index.render("Welcome to Play!"); + Content html = javaguide.test.junit5.html.index.render("Welcome to Play!"); assertEquals("text/html", html.contentType()); assertTrue(contentAsString(html).contains("Welcome to Play!")); } diff --git a/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/DatabaseTest.java b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/DatabaseTest.java index fa3460c55b3..d1751ce03ea 100644 --- a/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/DatabaseTest.java +++ b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/DatabaseTest.java @@ -18,7 +18,7 @@ class DatabaseTest { - Database database; + static Database database; @BeforeAll static void setupDatabase() { diff --git a/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/FakeApplicationTest.java b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/FakeApplicationTest.java index 1d2c64ffb96..73c81f10a02 100644 --- a/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/FakeApplicationTest.java +++ b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/FakeApplicationTest.java @@ -13,7 +13,7 @@ import org.junit.jupiter.api.Test; import play.Application; -class FakeApplicationTest { +public class FakeApplicationTest { public static class Computer { public String name = "Macintosh"; diff --git a/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/InjectionTest.java b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/InjectionTest.java index f659b0b8d44..1371c2fc3a9 100644 --- a/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/InjectionTest.java +++ b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/InjectionTest.java @@ -30,7 +30,7 @@ public void configure() { // #test-injection @RegisterExtension - static ApplicationExtension applicationExtension = new ApplicationExtension(createApplication()); + static ApplicationExtension appExtension = new ApplicationExtension(createApplication()); static Application createApplication() { GuiceApplicationBuilder builder = @@ -43,7 +43,7 @@ static Application createApplication() { @Test void testApplication() { - Application application = applicationExtension.getApplication(); + Application application = appExtension.getApplication(); assertNotNull(application); } } diff --git a/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/JavaTestingWithDatabases.java b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/JavaTestingWithDatabases.java index 450253446ce..3c3e6c03208 100644 --- a/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/JavaTestingWithDatabases.java +++ b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/JavaTestingWithDatabases.java @@ -48,7 +48,7 @@ static class NotTested { static class ExampleUnitTest { // #database-junit - Database database; + static Database database; @BeforeAll static void createDatabase() { diff --git a/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/guice/JavaGuiceApplicationBuilderTest.java b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/guice/JavaGuiceApplicationBuilderTest.java index 4820b09a7a4..686b7de836f 100644 --- a/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/guice/JavaGuiceApplicationBuilderTest.java +++ b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/guice/JavaGuiceApplicationBuilderTest.java @@ -20,7 +20,7 @@ import play.Environment; import play.Mode; import play.mvc.Result; -import router.Routes; +import javaguide.test.junit5.guice.Routes; // #builder-imports diff --git a/documentation/manual/working/javaGuide/main/upload/code/JavaFileUpload.java b/documentation/manual/working/javaGuide/main/upload/code/JavaFileUpload.java index 42239255bf7..f88ba5cf490 100644 --- a/documentation/manual/working/javaGuide/main/upload/code/JavaFileUpload.java +++ b/documentation/manual/working/javaGuide/main/upload/code/JavaFileUpload.java @@ -3,9 +3,9 @@ */ import static javaguide.testhelpers.MockJavaActionHelper.*; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.junit.Assert.assertThat; +import static org.junit.jupiter.api.Assertions.*; import static play.test.Helpers.contentAsString; +import static play.test.Helpers.fakeApplication; import static play.test.Helpers.fakeRequest; import akka.stream.IOResult; @@ -22,7 +22,8 @@ import java.util.concurrent.CompletionStage; import java.util.function.Function; import javax.inject.Inject; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import play.Application; import play.core.j.JavaHandlerComponents; import play.core.parsers.Multipart; import play.http.HttpErrorHandler; @@ -32,9 +33,13 @@ import play.mvc.Http; import play.mvc.Http.MultipartFormData.FilePart; import play.mvc.Result; -import play.test.WithApplication; +import play.test.junit5.ApplicationExtension; -public class JavaFileUpload extends WithApplication { +public class JavaFileUpload { + + static ApplicationExtension appExtension = new ApplicationExtension(fakeApplication()); + static Application app = appExtension.getApplication(); + static Materializer mat = appExtension.getMaterializer(); static class AsyncUpload extends Controller { // #asyncUpload @@ -102,7 +107,7 @@ private File generateTempFile() { // #customfileparthandler @Test - public void testCustomMultipart() throws IOException { + void testCustomMultipart() throws IOException { play.libs.Files.TemporaryFileCreator tfc = play.libs.Files.singletonTemporaryFileCreator(); Path tmpFile = Files.createTempFile("temp", "txt"); Files.write(tmpFile, "foo".getBytes()); @@ -110,10 +115,12 @@ public void testCustomMultipart() throws IOException { Http.MultipartFormData.FilePart> dp = new Http.MultipartFormData.FilePart<>( "name", "filename", "text/plain", source, Files.size(tmpFile)); - assertThat( + assertEquals( + "Got: file size = 3", contentAsString( call( - new javaguide.testhelpers.MockJavaAction(instanceOf(JavaHandlerComponents.class)) { + new javaguide.testhelpers.MockJavaAction( + app.injector().instanceOf(JavaHandlerComponents.class)) { @BodyParser.Of(MultipartFormDataWithFileBodyParser.class) public Result uploadCustomMultiPart(Http.Request request) throws Exception { final Http.MultipartFormData formData = @@ -126,7 +133,6 @@ public Result uploadCustomMultiPart(Http.Request request) throws Exception { } }, fakeRequest("POST", "/").bodyRaw(Collections.singletonList(dp), tfc, mat), - mat)), - equalTo("Got: file size = 3")); + mat))); } } diff --git a/documentation/manual/working/javaGuide/main/upload/code/JavaFileUploadTest.java b/documentation/manual/working/javaGuide/main/upload/code/JavaFileUploadTest.java index f743e36ef0c..456fa0995ba 100644 --- a/documentation/manual/working/javaGuide/main/upload/code/JavaFileUploadTest.java +++ b/documentation/manual/working/javaGuide/main/upload/code/JavaFileUploadTest.java @@ -2,7 +2,7 @@ * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. */ -import static org.junit.Assert.assertThat; +import static org.junit.jupiter.api.Assertions.assertTrue; import akka.stream.javadsl.FileIO; import akka.stream.javadsl.Source; @@ -11,20 +11,21 @@ import java.io.IOException; import java.nio.file.Files; import java.util.Collections; -import org.hamcrest.CoreMatchers; -import org.junit.Test; +import org.junit.jupiter.api.Test; import play.Application; import play.inject.guice.GuiceApplicationBuilder; import play.mvc.Http; import play.mvc.Result; import play.routing.Router; import play.test.Helpers; -import play.test.WithApplication; +import play.test.junit5.ApplicationExtension; -public class JavaFileUploadTest extends WithApplication { +public class JavaFileUploadTest { - @Override - protected Application provideApplication() { + static ApplicationExtension appExtension = new ApplicationExtension(createApplication()); + static Application app = appExtension.getApplication(); + + static Application createApplication() { Router router = Router.empty(); play.api.inject.guice.GuiceApplicationBuilder scalaBuilder = new play.api.inject.guice.GuiceApplicationBuilder().additionalRouter(router.asScala()); @@ -33,7 +34,7 @@ protected Application provideApplication() { // #testSyncUpload @Test - public void testFileUpload() throws IOException { + void testFileUpload() throws IOException { File file = getFile(); Http.MultipartFormData.Part> part = new Http.MultipartFormData.FilePart<>( @@ -55,8 +56,7 @@ public void testFileUpload() throws IOException { Result result = Helpers.route(app, request); String content = Helpers.contentAsString(result); - // ###replace: assertThat(content, CoreMatchers.equalTo("File uploaded")); - assertThat(content, CoreMatchers.containsString("Action Not Found")); + assertTrue(content.contains("Action Not Found")); } // #testSyncUpload diff --git a/documentation/manual/working/javaGuide/main/ws/code/javaguide/ws/Standalone.java b/documentation/manual/working/javaGuide/main/ws/code/javaguide/ws/Standalone.java index f429ff4847b..704de9e4ba5 100644 --- a/documentation/manual/working/javaGuide/main/ws/code/javaguide/ws/Standalone.java +++ b/documentation/manual/working/javaGuide/main/ws/code/javaguide/ws/Standalone.java @@ -13,7 +13,7 @@ import play.libs.ws.*; import play.libs.ws.ahc.*; -import org.junit.Test; +import org.junit.jupiter.api.Test; // #ws-standalone-imports import java.util.Optional; @@ -21,7 +21,7 @@ public class Standalone { @Test - public void testMe() { + void testMe() { // #ws-standalone // Set up Akka String name = "wsclient"; diff --git a/documentation/manual/working/javaGuide/main/ws/code/javaguide/ws/StandaloneWithConfig.java b/documentation/manual/working/javaGuide/main/ws/code/javaguide/ws/StandaloneWithConfig.java index 2e0cdf152e8..184bf5810db 100644 --- a/documentation/manual/working/javaGuide/main/ws/code/javaguide/ws/StandaloneWithConfig.java +++ b/documentation/manual/working/javaGuide/main/ws/code/javaguide/ws/StandaloneWithConfig.java @@ -9,7 +9,7 @@ import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import java.io.IOException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import play.api.libs.ws.WSConfigParser; import play.api.libs.ws.ahc.AhcConfigBuilder; import play.api.libs.ws.ahc.AhcWSClientConfig; From 2ac9d33599b0516342b5312e2f9c4a907046e82a Mon Sep 17 00:00:00 2001 From: "H. Habighorst" Date: Fri, 14 Jul 2023 22:40:23 +0200 Subject: [PATCH 10/15] #11839: fix formatting, add necessary annotation + import --- .../detailed/filters/FiltersTest.java | 3 +++ .../advanced/embedding/JavaEmbeddingPlay.java | 4 ++-- .../advanced/routing/JavaRoutingDsl.java | 2 ++ .../async/code/javaguide/async/JavaComet.java | 2 ++ .../code/javaguide/async/JavaStream.java | 3 +++ .../cache/code/javaguide/cache/JavaCache.java | 3 +++ .../code/javaguide/ehcache/JavaEhCache.java | 3 +++ .../javaguide/di/JavaDependencyInjection.java | 3 +++ .../forms/code/javaguide/forms/JavaCsrf.java | 3 +++ .../forms/code/javaguide/forms/JavaForms.java | 3 +++ .../forms/JavaFormsDirectFieldAccess.java | 3 +++ .../http/code/javaguide/http/JavaActions.java | 3 +++ .../code/javaguide/http/JavaBodyParsers.java | 3 +++ .../http/JavaContentNegotiation.java | 3 +++ .../code/javaguide/http/JavaResponse.java | 3 +++ .../code/javaguide/http/JavaSessionFlash.java | 24 +++++++++++-------- .../i18n/code/javaguide/i18n/JavaI18N.java | 4 ++++ .../code/javaguide/json/JavaJsonActions.java | 3 +++ .../code/javaguide/logging/JavaLogging.java | 2 +- .../main/upload/code/JavaFileUpload.java | 3 +++ .../main/upload/code/JavaFileUploadTest.java | 3 +++ 21 files changed, 70 insertions(+), 13 deletions(-) diff --git a/documentation/manual/working/commonGuide/filters/code/javaguide/detailed/filters/FiltersTest.java b/documentation/manual/working/commonGuide/filters/code/javaguide/detailed/filters/FiltersTest.java index 43b6290e354..c792e8c0c0a 100644 --- a/documentation/manual/working/commonGuide/filters/code/javaguide/detailed/filters/FiltersTest.java +++ b/documentation/manual/working/commonGuide/filters/code/javaguide/detailed/filters/FiltersTest.java @@ -8,6 +8,7 @@ import static play.test.Helpers.POST; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import play.Application; import play.api.test.CSRFTokenHelper; import play.mvc.Http; @@ -19,7 +20,9 @@ public class FiltersTest { + @RegisterExtension static ApplicationExtension appExtension = new ApplicationExtension(Helpers.fakeApplication()); + static Application app = appExtension.getApplication(); @Test diff --git a/documentation/manual/working/javaGuide/advanced/embedding/code/javaguide/advanced/embedding/JavaEmbeddingPlay.java b/documentation/manual/working/javaGuide/advanced/embedding/code/javaguide/advanced/embedding/JavaEmbeddingPlay.java index 04f045594be..afaf9725588 100644 --- a/documentation/manual/working/javaGuide/advanced/embedding/code/javaguide/advanced/embedding/JavaEmbeddingPlay.java +++ b/documentation/manual/working/javaGuide/advanced/embedding/code/javaguide/advanced/embedding/JavaEmbeddingPlay.java @@ -26,7 +26,7 @@ public class JavaEmbeddingPlay { @Test - void simple() throws Exception { + void simple() throws Exception { // #simple Server server = Server.forRouter( @@ -58,7 +58,7 @@ void simple() throws Exception { } @Test - void config() throws Exception { + void config() throws Exception { // #config Server server = Server.forRouter( diff --git a/documentation/manual/working/javaGuide/advanced/routing/code/javaguide/advanced/routing/JavaRoutingDsl.java b/documentation/manual/working/javaGuide/advanced/routing/code/javaguide/advanced/routing/JavaRoutingDsl.java index 8f7a1b6c21c..1dba80743b4 100644 --- a/documentation/manual/working/javaGuide/advanced/routing/code/javaguide/advanced/routing/JavaRoutingDsl.java +++ b/documentation/manual/working/javaGuide/advanced/routing/code/javaguide/advanced/routing/JavaRoutingDsl.java @@ -6,6 +6,7 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; // #imports import javax.inject.Inject; @@ -30,6 +31,7 @@ public class JavaRoutingDsl { + @RegisterExtension static ApplicationExtension appExtension = new ApplicationExtension(fakeApplication()); static Application app = appExtension.getApplication(); static RoutingDsl routingDsl; diff --git a/documentation/manual/working/javaGuide/main/async/code/javaguide/async/JavaComet.java b/documentation/manual/working/javaGuide/main/async/code/javaguide/async/JavaComet.java index a8ea283785b..6fa7cc73612 100644 --- a/documentation/manual/working/javaGuide/main/async/code/javaguide/async/JavaComet.java +++ b/documentation/manual/working/javaGuide/main/async/code/javaguide/async/JavaComet.java @@ -9,6 +9,7 @@ import javaguide.testhelpers.MockJavaAction; import javaguide.testhelpers.MockJavaActionHelper; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; // #comet-imports import akka.NotUsed; @@ -33,6 +34,7 @@ public class JavaComet { + @RegisterExtension static ApplicationExtension appExtension = new ApplicationExtension(fakeApplication()); static Application app = appExtension.getApplication(); static Materializer mat = appExtension.getMaterializer(); diff --git a/documentation/manual/working/javaGuide/main/async/code/javaguide/async/JavaStream.java b/documentation/manual/working/javaGuide/main/async/code/javaguide/async/JavaStream.java index adeb1a3ce3c..90fec40539a 100644 --- a/documentation/manual/working/javaGuide/main/async/code/javaguide/async/JavaStream.java +++ b/documentation/manual/working/javaGuide/main/async/code/javaguide/async/JavaStream.java @@ -21,6 +21,7 @@ import java.util.Optional; import javaguide.testhelpers.MockJavaAction; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import play.Application; import play.core.j.JavaHandlerComponents; import play.http.HttpEntity; @@ -30,7 +31,9 @@ public class JavaStream { + @RegisterExtension static ApplicationExtension appExtension = new ApplicationExtension(fakeApplication()); + static Application app = appExtension.getApplication(); static Materializer mat = appExtension.getMaterializer(); diff --git a/documentation/manual/working/javaGuide/main/cache/code/javaguide/cache/JavaCache.java b/documentation/manual/working/javaGuide/main/cache/code/javaguide/cache/JavaCache.java index 881e03413f2..750d4ca5922 100644 --- a/documentation/manual/working/javaGuide/main/cache/code/javaguide/cache/JavaCache.java +++ b/documentation/manual/working/javaGuide/main/cache/code/javaguide/cache/JavaCache.java @@ -17,6 +17,7 @@ import java.util.concurrent.CompletionStage; import javaguide.testhelpers.MockJavaAction; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import play.Application; import play.cache.AsyncCacheApi; import play.cache.Cached; @@ -26,11 +27,13 @@ public class JavaCache { + @RegisterExtension static ApplicationExtension appExtension = new ApplicationExtension( fakeApplication( ImmutableMap.of( "play.cache.bindCaches", Collections.singletonList("session-cache")))); + static Application app = appExtension.getApplication(); static Materializer mat = appExtension.getMaterializer(); diff --git a/documentation/manual/working/javaGuide/main/cache/code/javaguide/ehcache/JavaEhCache.java b/documentation/manual/working/javaGuide/main/cache/code/javaguide/ehcache/JavaEhCache.java index 3ae51aa1293..ad4867abca3 100755 --- a/documentation/manual/working/javaGuide/main/cache/code/javaguide/ehcache/JavaEhCache.java +++ b/documentation/manual/working/javaGuide/main/cache/code/javaguide/ehcache/JavaEhCache.java @@ -18,6 +18,7 @@ import javaguide.testhelpers.MockJavaAction; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import play.Application; import play.cache.AsyncCacheApi; import play.cache.Cached; @@ -27,11 +28,13 @@ public class JavaEhCache { + @RegisterExtension static ApplicationExtension appExtension = new ApplicationExtension( fakeApplication( ImmutableMap.of( "play.cache.bindCaches", Collections.singletonList("session-cache")))); + static Application app = appExtension.getApplication(); static Materializer mat = appExtension.getMaterializer(); diff --git a/documentation/manual/working/javaGuide/main/dependencyinjection/code/javaguide/di/JavaDependencyInjection.java b/documentation/manual/working/javaGuide/main/dependencyinjection/code/javaguide/di/JavaDependencyInjection.java index 8d707ed3824..195dcc32628 100644 --- a/documentation/manual/working/javaGuide/main/dependencyinjection/code/javaguide/di/JavaDependencyInjection.java +++ b/documentation/manual/working/javaGuide/main/dependencyinjection/code/javaguide/di/JavaDependencyInjection.java @@ -8,13 +8,16 @@ import static play.test.Helpers.*; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import play.Application; import play.test.*; import play.test.junit5.ApplicationExtension; public class JavaDependencyInjection { + @RegisterExtension static ApplicationExtension appExtension = new ApplicationExtension(fakeApplication()); + static Application app = appExtension.getApplication(); @Test diff --git a/documentation/manual/working/javaGuide/main/forms/code/javaguide/forms/JavaCsrf.java b/documentation/manual/working/javaGuide/main/forms/code/javaguide/forms/JavaCsrf.java index 7d1b30dec17..9659fc43c02 100644 --- a/documentation/manual/working/javaGuide/main/forms/code/javaguide/forms/JavaCsrf.java +++ b/documentation/manual/working/javaGuide/main/forms/code/javaguide/forms/JavaCsrf.java @@ -15,6 +15,7 @@ import java.util.regex.Pattern; import javaguide.testhelpers.MockJavaAction; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import play.Application; import play.core.j.JavaHandlerComponents; import play.filters.csrf.AddCSRFToken; @@ -27,7 +28,9 @@ public class JavaCsrf { + @RegisterExtension static ApplicationExtension appExtension = new ApplicationExtension(fakeApplication()); + static Application app = appExtension.getApplication(); static Materializer mat = appExtension.getMaterializer(); diff --git a/documentation/manual/working/javaGuide/main/forms/code/javaguide/forms/JavaForms.java b/documentation/manual/working/javaGuide/main/forms/code/javaguide/forms/JavaForms.java index 90d85fa1d39..3f6333bcec3 100644 --- a/documentation/manual/working/javaGuide/main/forms/code/javaguide/forms/JavaForms.java +++ b/documentation/manual/working/javaGuide/main/forms/code/javaguide/forms/JavaForms.java @@ -22,6 +22,7 @@ import javaguide.testhelpers.MockJavaAction; import javax.validation.groups.Default; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import play.Application; import play.core.j.JavaHandlerComponents; import play.data.DynamicForm; @@ -45,7 +46,9 @@ public class JavaForms { + @RegisterExtension static ApplicationExtension appExtension = new ApplicationExtension(fakeApplication()); + static Application app = appExtension.getApplication(); static Materializer mat = appExtension.getMaterializer(); diff --git a/documentation/manual/working/javaGuide/main/forms/code/javaguide/forms/JavaFormsDirectFieldAccess.java b/documentation/manual/working/javaGuide/main/forms/code/javaguide/forms/JavaFormsDirectFieldAccess.java index 60b8b994d89..5d57c2875ff 100644 --- a/documentation/manual/working/javaGuide/main/forms/code/javaguide/forms/JavaFormsDirectFieldAccess.java +++ b/documentation/manual/working/javaGuide/main/forms/code/javaguide/forms/JavaFormsDirectFieldAccess.java @@ -12,6 +12,7 @@ import java.util.Map; import javaguide.forms.u4.User; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import play.Application; import play.data.Form; import play.data.FormFactory; @@ -21,7 +22,9 @@ public class JavaFormsDirectFieldAccess { + @RegisterExtension static ApplicationExtension appExtension = new ApplicationExtension(fakeApplication()); + static Application app = appExtension.getApplication(); private FormFactory formFactory() { diff --git a/documentation/manual/working/javaGuide/main/http/code/javaguide/http/JavaActions.java b/documentation/manual/working/javaGuide/main/http/code/javaguide/http/JavaActions.java index b90818ed75a..af79f58a041 100644 --- a/documentation/manual/working/javaGuide/main/http/code/javaguide/http/JavaActions.java +++ b/documentation/manual/working/javaGuide/main/http/code/javaguide/http/JavaActions.java @@ -14,6 +14,7 @@ import java.util.concurrent.CompletionStage; import javaguide.testhelpers.MockJavaAction; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import play.Application; import play.core.j.JavaHandlerComponents; import play.mvc.Controller; @@ -23,7 +24,9 @@ public class JavaActions { + @RegisterExtension static ApplicationExtension appExtension = new ApplicationExtension(fakeApplication()); + static Application app = appExtension.getApplication(); static Materializer mat = appExtension.getMaterializer(); diff --git a/documentation/manual/working/javaGuide/main/http/code/javaguide/http/JavaBodyParsers.java b/documentation/manual/working/javaGuide/main/http/code/javaguide/http/JavaBodyParsers.java index ee668c865b4..86853c3d60c 100644 --- a/documentation/manual/working/javaGuide/main/http/code/javaguide/http/JavaBodyParsers.java +++ b/documentation/manual/working/javaGuide/main/http/code/javaguide/http/JavaBodyParsers.java @@ -18,6 +18,7 @@ import javaguide.testhelpers.MockJavaAction; import javax.inject.Inject; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import play.Application; import play.core.j.JavaHandlerComponents; import play.http.HttpErrorHandler; @@ -32,7 +33,9 @@ public class JavaBodyParsers { + @RegisterExtension static ApplicationExtension appExtension = new ApplicationExtension(fakeApplication()); + static Application app = appExtension.getApplication(); static Materializer mat = appExtension.getMaterializer(); diff --git a/documentation/manual/working/javaGuide/main/http/code/javaguide/http/JavaContentNegotiation.java b/documentation/manual/working/javaGuide/main/http/code/javaguide/http/JavaContentNegotiation.java index f35c04a1af0..93453fab9df 100644 --- a/documentation/manual/working/javaGuide/main/http/code/javaguide/http/JavaContentNegotiation.java +++ b/documentation/manual/working/javaGuide/main/http/code/javaguide/http/JavaContentNegotiation.java @@ -13,6 +13,7 @@ import java.util.List; import javaguide.testhelpers.MockJavaAction; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import play.Application; import play.core.j.JavaHandlerComponents; import play.libs.Json; @@ -21,7 +22,9 @@ public class JavaContentNegotiation { + @RegisterExtension static ApplicationExtension appExtension = new ApplicationExtension(fakeApplication()); + static Application app = appExtension.getApplication(); static Materializer mat = appExtension.getMaterializer(); diff --git a/documentation/manual/working/javaGuide/main/http/code/javaguide/http/JavaResponse.java b/documentation/manual/working/javaGuide/main/http/code/javaguide/http/JavaResponse.java index 5aa8784902e..877e8948fc8 100644 --- a/documentation/manual/working/javaGuide/main/http/code/javaguide/http/JavaResponse.java +++ b/documentation/manual/working/javaGuide/main/http/code/javaguide/http/JavaResponse.java @@ -24,6 +24,7 @@ import java.util.stream.Collectors; import javaguide.testhelpers.MockJavaAction; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import play.Application; import play.core.j.JavaHandlerComponents; import play.libs.Json; @@ -37,7 +38,9 @@ public class JavaResponse { + @RegisterExtension static ApplicationExtension appExtension = new ApplicationExtension(fakeApplication()); + static Application app = appExtension.getApplication(); static Materializer mat = appExtension.getMaterializer(); diff --git a/documentation/manual/working/javaGuide/main/http/code/javaguide/http/JavaSessionFlash.java b/documentation/manual/working/javaGuide/main/http/code/javaguide/http/JavaSessionFlash.java index b49f17f0c43..3e93b815d2d 100644 --- a/documentation/manual/working/javaGuide/main/http/code/javaguide/http/JavaSessionFlash.java +++ b/documentation/manual/working/javaGuide/main/http/code/javaguide/http/JavaSessionFlash.java @@ -6,6 +6,7 @@ import akka.stream.Materializer; import org.junit.jupiter.api.*; +import org.junit.jupiter.api.extension.RegisterExtension; import play.core.j.JavaHandlerComponents; import javaguide.testhelpers.MockJavaAction; import play.Application; @@ -22,11 +23,14 @@ import static play.test.Helpers.*; public class JavaSessionFlash { - static ApplicationExtension appExtension = new ApplicationExtension(fakeApplication()); - static Application app = appExtension.getApplication(); - static Materializer mat = appExtension.getMaterializer(); + + @RegisterExtension + static ApplicationExtension appExtension = new ApplicationExtension(fakeApplication()); + static Application app = appExtension.getApplication(); + static Materializer mat = appExtension.getMaterializer(); + @Test - void readSession() { + void readSession() { assertEquals( "Hello foo", contentAsString( @@ -47,7 +51,7 @@ public Result index(Http.Request request) { } @Test - void storeSession() { + void storeSession() { Session session = call( new MockJavaAction(app.injector().instanceOf(JavaHandlerComponents.class)) { @@ -65,7 +69,7 @@ public Result login(Http.Request request) { } @Test - void removeFromSession() { + void removeFromSession() { Session session = call( new MockJavaAction(app.injector().instanceOf(JavaHandlerComponents.class)) { @@ -82,7 +86,7 @@ public Result logout(Http.Request request) { } @Test - void discardWholeSession() { + void discardWholeSession() { Session session = call( new MockJavaAction(app.injector().instanceOf(JavaHandlerComponents.class)) { @@ -99,7 +103,7 @@ public Result logout() { } @Test - void readFlash() { + void readFlash() { assertEquals( "hi", contentAsString( @@ -116,7 +120,7 @@ public Result index(Http.Request request) { } @Test - void storeFlash() { + void storeFlash() { Flash flash = call( new MockJavaAction(app.injector().instanceOf(JavaHandlerComponents.class)) { @@ -133,7 +137,7 @@ public Result save() { } @Test - void accessFlashInTemplate() { + void accessFlashInTemplate() { MockJavaAction index = new MockJavaAction(app.injector().instanceOf(JavaHandlerComponents.class)) { public Result index(Http.Request request) { diff --git a/documentation/manual/working/javaGuide/main/i18n/code/javaguide/i18n/JavaI18N.java b/documentation/manual/working/javaGuide/main/i18n/code/javaguide/i18n/JavaI18N.java index b484000cbf8..4db30056bba 100644 --- a/documentation/manual/working/javaGuide/main/i18n/code/javaguide/i18n/JavaI18N.java +++ b/documentation/manual/working/javaGuide/main/i18n/code/javaguide/i18n/JavaI18N.java @@ -17,6 +17,7 @@ import javaguide.testhelpers.MockJavaAction; import javaguide.testhelpers.MockJavaActionHelper; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import play.Application; import play.core.j.JavaHandlerComponents; import play.i18n.Lang; @@ -27,6 +28,8 @@ import play.test.junit5.ApplicationExtension; public class JavaI18N { + + @RegisterExtension static ApplicationExtension appExtension = new ApplicationExtension( fakeApplication( @@ -35,6 +38,7 @@ public class JavaI18N { ImmutableList.of("en", "en-US", "fr"), "messages.path", "javaguide/i18n"))); + static Application app = appExtension.getApplication(); static Materializer mat = appExtension.getMaterializer(); diff --git a/documentation/manual/working/javaGuide/main/json/code/javaguide/json/JavaJsonActions.java b/documentation/manual/working/javaGuide/main/json/code/javaguide/json/JavaJsonActions.java index dcb1ed1c9c6..78b77c269f1 100644 --- a/documentation/manual/working/javaGuide/main/json/code/javaguide/json/JavaJsonActions.java +++ b/documentation/manual/working/javaGuide/main/json/code/javaguide/json/JavaJsonActions.java @@ -16,6 +16,7 @@ import java.util.Optional; import javaguide.testhelpers.MockJavaAction; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import play.Application; import play.core.j.JavaHandlerComponents; import play.libs.Json; @@ -26,7 +27,9 @@ public class JavaJsonActions { + @RegisterExtension static ApplicationExtension appExtension = new ApplicationExtension(fakeApplication()); + static Application app = appExtension.getApplication(); static Materializer mat = appExtension.getMaterializer(); diff --git a/documentation/manual/working/javaGuide/main/logging/code/javaguide/logging/JavaLogging.java b/documentation/manual/working/javaGuide/main/logging/code/javaguide/logging/JavaLogging.java index b8e6d8d2d4b..b92e16dafde 100644 --- a/documentation/manual/working/javaGuide/main/logging/code/javaguide/logging/JavaLogging.java +++ b/documentation/manual/working/javaGuide/main/logging/code/javaguide/logging/JavaLogging.java @@ -38,7 +38,7 @@ public void testDefaultLogger() { } @Test - void testCreateLogger() { + void testCreateLogger() { // #logging-create-logger-name final Logger accessLogger = LoggerFactory.getLogger("access"); diff --git a/documentation/manual/working/javaGuide/main/upload/code/JavaFileUpload.java b/documentation/manual/working/javaGuide/main/upload/code/JavaFileUpload.java index f88ba5cf490..95bc92ff441 100644 --- a/documentation/manual/working/javaGuide/main/upload/code/JavaFileUpload.java +++ b/documentation/manual/working/javaGuide/main/upload/code/JavaFileUpload.java @@ -23,6 +23,7 @@ import java.util.function.Function; import javax.inject.Inject; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import play.Application; import play.core.j.JavaHandlerComponents; import play.core.parsers.Multipart; @@ -37,7 +38,9 @@ public class JavaFileUpload { + @RegisterExtension static ApplicationExtension appExtension = new ApplicationExtension(fakeApplication()); + static Application app = appExtension.getApplication(); static Materializer mat = appExtension.getMaterializer(); diff --git a/documentation/manual/working/javaGuide/main/upload/code/JavaFileUploadTest.java b/documentation/manual/working/javaGuide/main/upload/code/JavaFileUploadTest.java index 456fa0995ba..c57cf2b3ba1 100644 --- a/documentation/manual/working/javaGuide/main/upload/code/JavaFileUploadTest.java +++ b/documentation/manual/working/javaGuide/main/upload/code/JavaFileUploadTest.java @@ -12,6 +12,7 @@ import java.nio.file.Files; import java.util.Collections; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import play.Application; import play.inject.guice.GuiceApplicationBuilder; import play.mvc.Http; @@ -22,7 +23,9 @@ public class JavaFileUploadTest { + @RegisterExtension static ApplicationExtension appExtension = new ApplicationExtension(createApplication()); + static Application app = appExtension.getApplication(); static Application createApplication() { From d0626457fe174223a68e11352941ed181976b0e5 Mon Sep 17 00:00:00 2001 From: "H. Habighorst" Date: Fri, 14 Jul 2023 23:03:26 +0200 Subject: [PATCH 11/15] #11839: remove junit4 tests & project dependency, enable junit5 test runner --- documentation/build.sbt | 5 +- .../main/tests/JavaFunctionalTest.md | 28 ++--- .../tests/code/javaguide.test.junit4.routes | 4 - .../test/junit4/BrowserFunctionalTest.java | 22 ---- .../javaguide/test/junit4/FunctionalTest.java | 100 ------------------ .../test/junit4/ServerFunctionalTest.java | 41 ------- .../junit4/controllers/HomeController.java | 18 ---- .../javaguide/test/junit4/index.scala.html | 4 - documentation/project/plugins.sbt | 3 + 9 files changed, 12 insertions(+), 213 deletions(-) delete mode 100644 documentation/manual/working/javaGuide/main/tests/code/javaguide.test.junit4.routes delete mode 100644 documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit4/BrowserFunctionalTest.java delete mode 100644 documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit4/FunctionalTest.java delete mode 100644 documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit4/ServerFunctionalTest.java delete mode 100644 documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit4/controllers/HomeController.java delete mode 100644 documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit4/index.scala.html diff --git a/documentation/build.sbt b/documentation/build.sbt index 2cdaf0893f8..536daa5b577 100644 --- a/documentation/build.sbt +++ b/documentation/build.sbt @@ -44,7 +44,9 @@ lazy val main = Project("Play-Documentation", file(".")) "com.h2database" % "h2" % "2.1.214" % Test, "org.mockito" % "mockito-core" % "5.4.0" % Test, // https://github.com/logstash/logstash-logback-encoder/tree/logstash-logback-encoder-4.9#including - "net.logstash.logback" % "logstash-logback-encoder" % "7.3" % Test + "net.logstash.logback" % "logstash-logback-encoder" % "7.3" % Test, + // JUnit 5 testing + "net.aichler" % "jupiter-interface" % JupiterKeys.jupiterVersion.value % Test, ), PlayDocsKeys.docsJarFile := Some((playDocs / Compile / packageBin).value), PlayDocsKeys.playDocsValidationConfig := PlayDocsValidation.ValidationConfig( @@ -117,7 +119,6 @@ lazy val main = Project("Play-Documentation", file(".")) playDocs, playProject("Play") % "test", playProject("Play-Specs2") % "test", - playProject("Play-Test-JUnit4") % "test", playProject("Play-Test-JUnit5") % "test", playProject("Play-Java") % "test", playProject("Play-Java-Forms") % "test", diff --git a/documentation/manual/working/javaGuide/main/tests/JavaFunctionalTest.md b/documentation/manual/working/javaGuide/main/tests/JavaFunctionalTest.md index 09bbfc56202..21154da235b 100644 --- a/documentation/manual/working/javaGuide/main/tests/JavaFunctionalTest.md +++ b/documentation/manual/working/javaGuide/main/tests/JavaFunctionalTest.md @@ -53,40 +53,24 @@ Note that there are different ways to customize the `Application` creation when To run JUnit 4 tests with an application, one can extend [`WithApplication`](api/java/play/test/junit4/WithApplication.html). -This will automatically ensure that an application is started and stopped for each test method: - -@[test-withapp](code/javaguide/test/junit4/FunctionalTest.java) +This will automatically ensure that an application is started and stopped for each test method. ## Testing a Controller Action through Routing -With a running application, you can retrieve an action reference from the path for a route and invoke it. This also allows you to use `RequestBuilder` which creates a fake request: - -@[bad-route-import](code/javaguide/test/junit4/FunctionalTest.java) - -@[bad-route](code/javaguide/test/junit4/FunctionalTest.java) - -It is also possible to create the `RequestBuilder` using the reverse router directly and avoid hard-coding the router path: +With a running application, you can retrieve an action reference from the path for a route and invoke it. This also allows you to use `RequestBuilder` which creates a fake request. -@[good-route](code/javaguide/test/junit4/FunctionalTest.java) +It is also possible to create the `RequestBuilder` using the reverse router directly and avoid hard-coding the router path. > **Note:** the reverse router is not executing the action, but instead only providing a `Call` with information that will be used to create the `RequestBuilder` and later invoke the the action itself using `Helpers.route(Application, RequestBuilder)`. That is why it is not necessary to pass a `Http.Request` when using the reverse router to create the `Http.RequestBuilder` in tests even if the action is receiving a `Http.Request` as a parameter. ## Testing with a server -Sometimes you want to test the real HTTP stack from within your test. You can do this by starting a test server: +Sometimes you want to test the real HTTP stack from within your test. You can do this by starting a test server. -@[test-server](code/javaguide/test/junit4/FunctionalTest.java) - -Just as there exists a `WithApplication` class, there is also a [`WithServer`](api/java/play/test/junit4/WithBrowser.html) which you can extend to automatically start and stop a [`TestServer`](api/java/play/test/TestServer.html) for your tests: - -@[test-withserver](code/javaguide/test/junit4/ServerFunctionalTest.java) +Just as there exists a `WithApplication` class, there is also a [`WithServer`](api/java/play/test/junit4/WithBrowser.html) which you can extend to automatically start and stop a [`TestServer`](api/java/play/test/TestServer.html) for your tests. ## Testing with a browser If you want to test your application from with a Web browser, you can use [Selenium WebDriver](https://github.com/seleniumhq/selenium). Play will start the WebDriver for you, and wrap it in the convenient API provided by [FluentLenium](https://github.com/FluentLenium/FluentLenium). -@[test-browser](code/javaguide/test/junit4/FunctionalTest.java) - -And, of course there, is the [`WithBrowser`](api/java/play/test/junit4/WithBrowser.html) class to automatically open and close a browser for each test: - -@[test-withbrowser](code/javaguide/test/junit4/BrowserFunctionalTest.java) +And, of course there, is the [`WithBrowser`](api/java/play/test/junit4/WithBrowser.html) class to automatically open and close a browser for each test. \ No newline at end of file diff --git a/documentation/manual/working/javaGuide/main/tests/code/javaguide.test.junit4.routes b/documentation/manual/working/javaGuide/main/tests/code/javaguide.test.junit4.routes deleted file mode 100644 index 080c01f7d2f..00000000000 --- a/documentation/manual/working/javaGuide/main/tests/code/javaguide.test.junit4.routes +++ /dev/null @@ -1,4 +0,0 @@ -# Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. - -GET / controllers.HomeController.index() -POST / controllers.HomeController.post(request: Request) \ No newline at end of file diff --git a/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit4/BrowserFunctionalTest.java b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit4/BrowserFunctionalTest.java deleted file mode 100644 index 6efa885db01..00000000000 --- a/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit4/BrowserFunctionalTest.java +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. - */ - -package javaguide.test.junit4; - -import static org.junit.Assert.*; - -import org.junit.*; -import play.test.*; -import play.test.junit4.*; - -// #test-withbrowser -public class BrowserFunctionalTest extends WithBrowser { - - @Test - public void runInBrowser() { - browser.goTo("/"); - assertNotNull(browser.el("title").text()); - } -} -// #test-withbrowser diff --git a/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit4/FunctionalTest.java b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit4/FunctionalTest.java deleted file mode 100644 index ec717b25404..00000000000 --- a/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit4/FunctionalTest.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. - */ - -package javaguide.test.junit4; - -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.*; - -import org.junit.*; - -import play.mvc.*; -import play.test.*; -import play.test.junit4.*; -import play.libs.ws.*; - -import static play.test.Helpers.*; -import static org.junit.Assert.*; - -// #bad-route-import -import play.mvc.Http.RequestBuilder; -// #bad-route-import - -import javaguide.test.junit4.controllers.routes; - -// #test-withapp -public class FunctionalTest extends WithApplication { - // #test-withapp - - // #bad-route - @Test - public void testBadRoute() { - RequestBuilder request = Helpers.fakeRequest().method(GET).uri("/xx/Kiwi"); - - Result result = route(app, request); - assertEquals(NOT_FOUND, result.status()); - } - // #bad-route - - // #good-route - @Test - public void testGoodRouteCall() { - RequestBuilder request = Helpers.fakeRequest(routes.HomeController.index()); - - Result result = route(app, request); - // ###replace: assertEquals(OK, result.status()); - assertEquals(NOT_FOUND, result.status()); // NOT_FOUND since the routes files aren't used - } - // #good-route - - int timeout = 5000; - - private TestServer testServer() { - Map config = new HashMap(); - config.put("play.http.router", "javaguide.test.junit4.Routes"); - return Helpers.testServer(fakeApplication(config)); - } - - private TestServer testServer(int port) { - Map config = new HashMap(); - config.put("play.http.router", "javaguide.test.junit4.Routes"); - return Helpers.testServer(port, fakeApplication(config)); - } - - private org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger("application"); - - // #test-server - @Test - public void testInServer() throws Exception { - TestServer server = testServer(3333); - running( - server, - () -> { - try (WSClient ws = WSTestClient.newClient(3333)) { - CompletionStage completionStage = ws.url("/").get(); - WSResponse response = completionStage.toCompletableFuture().get(); - assertEquals(OK, response.getStatus()); - } catch (Exception e) { - logger.error(e.getMessage(), e); - } - }); - } - // #test-server - - // #test-browser - @Test - public void runInBrowser() { - running( - testServer(), - HTMLUNIT, - browser -> { - browser.goTo("/"); - assertEquals("Welcome to Play!", browser.el("#title").text()); - browser.$("a").click(); - assertEquals("login", browser.url()); - }); - } - // #test-browser -} diff --git a/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit4/ServerFunctionalTest.java b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit4/ServerFunctionalTest.java deleted file mode 100644 index e2c0be1d49e..00000000000 --- a/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit4/ServerFunctionalTest.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. - */ - -package javaguide.test.junit4; - -import static org.junit.Assert.*; -import static play.test.Helpers.NOT_FOUND; - -import java.util.OptionalInt; -import java.util.concurrent.*; -import org.junit.*; -import play.libs.ws.*; -import play.test.*; -import play.test.junit4.*; - -// #test-withserver -public class ServerFunctionalTest extends WithServer { - - @Test - public void testInServer() throws Exception { - OptionalInt optHttpsPort = testServer.getRunningHttpsPort(); - String url; - int port; - if (optHttpsPort.isPresent()) { - port = optHttpsPort.getAsInt(); - url = "https://localhost:" + port; - } else { - port = testServer.getRunningHttpPort().getAsInt(); - url = "http://localhost:" + port; - } - try (WSClient ws = play.test.WSTestClient.newClient(port)) { - CompletionStage stage = ws.url(url).get(); - WSResponse response = stage.toCompletableFuture().get(); - assertEquals(NOT_FOUND, response.getStatus()); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } -} -// #test-withserver diff --git a/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit4/controllers/HomeController.java b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit4/controllers/HomeController.java deleted file mode 100644 index 5af9b19225c..00000000000 --- a/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit4/controllers/HomeController.java +++ /dev/null @@ -1,18 +0,0 @@ -/* - * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. - */ - -package javaguide.test.junit4.controllers; - -import play.mvc.*; - -public class HomeController extends Controller { - - public Result index() { - return ok(javaguide.test.junit4.html.index.render("Welcome to Play!")); - } - - public Result post(Http.Request request) { - return redirect(routes.HomeController.index()); - } -} diff --git a/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit4/index.scala.html b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit4/index.scala.html deleted file mode 100644 index b73b280cf40..00000000000 --- a/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit4/index.scala.html +++ /dev/null @@ -1,4 +0,0 @@ -@(title: String) - -

@title

-click me diff --git a/documentation/project/plugins.sbt b/documentation/project/plugins.sbt index 20452668b36..17598d722f2 100644 --- a/documentation/project/plugins.sbt +++ b/documentation/project/plugins.sbt @@ -20,3 +20,6 @@ addSbtPlugin("com.typesafe.play" % "sbt-twirl" % "1.6.0-RC4") // sync with proje // Required for IDE docs addSbtPlugin("com.github.sbt" % "sbt-eclipse" % "6.0.0") + +// Required for JUnit 5 tests +addSbtPlugin("net.aichler" % "sbt-jupiter-interface" % "0.11.1") From fdfbc70c0ceec67f9f816621ac058aa370eb6b22 Mon Sep 17 00:00:00 2001 From: "H. Habighorst" Date: Sat, 15 Jul 2023 00:18:04 +0200 Subject: [PATCH 12/15] #11839: sbt-test/play-sbt-plugin: migrate to junit5, fix controllers package vs controller dir --- .../java-test-helpers/build.sbt | 16 +++++-- .../java-test-helpers/project/plugins.sbt | 5 ++- .../HomeController.java | 0 .../java/controllers/HomeControllerTest.java | 44 +++++++++++-------- 4 files changed, 41 insertions(+), 24 deletions(-) rename dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/java-test-helpers/src/main/java/{controller => controllers}/HomeController.java (100%) diff --git a/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/java-test-helpers/build.sbt b/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/java-test-helpers/build.sbt index 07e7995071e..dbbe5e56fac 100644 --- a/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/java-test-helpers/build.sbt +++ b/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/java-test-helpers/build.sbt @@ -1,17 +1,25 @@ // Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. +import play.core.PlayVersion + name := """java-test-helpers""" organization := "com.example" version := "1.0-SNAPSHOT" lazy val root = (project in file(".")) + .settings( + libraryDependencies ++= Seq( + guice, + "com.typesafe.play" %% "play-test-junit5" % PlayVersion.current % "test", + ), + scalaVersion := ScriptedTools.scalaVersionFromJavaProperties(), + updateOptions := updateOptions.value.withLatestSnapshots(false), + update / evictionWarningOptions ~= (_.withWarnTransitiveEvictions(false).withWarnDirectEvictions(false)), + ) .enablePlugins(PlayJava) // disable PlayLayoutPlugin because the `test` file used by `sbt-scripted` collides with the `test/` Play expects. .disablePlugins(PlayLayoutPlugin) -scalaVersion := ScriptedTools.scalaVersionFromJavaProperties() -updateOptions := updateOptions.value.withLatestSnapshots(false) -update / evictionWarningOptions ~= (_.withWarnTransitiveEvictions(false).withWarnDirectEvictions(false)) -libraryDependencies += guice + diff --git a/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/java-test-helpers/project/plugins.sbt b/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/java-test-helpers/project/plugins.sbt index b79417abc48..7c1e60bdd65 100644 --- a/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/java-test-helpers/project/plugins.sbt +++ b/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/java-test-helpers/project/plugins.sbt @@ -1,5 +1,6 @@ // Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. updateOptions := updateOptions.value.withLatestSnapshots(false) -addSbtPlugin("com.typesafe.play" % "sbt-plugin" % sys.props("project.version")) -addSbtPlugin("com.typesafe.play" % "sbt-scripted-tools" % sys.props("project.version")) +addSbtPlugin("com.typesafe.play" % "sbt-plugin" % sys.props("project.version")) +addSbtPlugin("com.typesafe.play" % "sbt-scripted-tools" % sys.props("project.version")) +addSbtPlugin("net.aichler" % "sbt-jupiter-interface" % "0.11.1") \ No newline at end of file diff --git a/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/java-test-helpers/src/main/java/controller/HomeController.java b/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/java-test-helpers/src/main/java/controllers/HomeController.java similarity index 100% rename from dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/java-test-helpers/src/main/java/controller/HomeController.java rename to dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/java-test-helpers/src/main/java/controllers/HomeController.java diff --git a/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/java-test-helpers/src/test/java/controllers/HomeControllerTest.java b/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/java-test-helpers/src/test/java/controllers/HomeControllerTest.java index f1aa430a9e1..0ba43d91157 100644 --- a/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/java-test-helpers/src/test/java/controllers/HomeControllerTest.java +++ b/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/java-test-helpers/src/test/java/controllers/HomeControllerTest.java @@ -10,28 +10,34 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; +import akka.stream.Materializer; import akka.util.ByteString; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import play.Application; import play.libs.Files; import play.mvc.Http; import play.mvc.Result; -import play.test.WithApplication; +import play.test.junit5.ApplicationExtension; import static java.nio.file.Files.write; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import static play.mvc.Http.Status.OK; import static play.test.Helpers.POST; import static play.test.Helpers.route; +import static play.test.Helpers.fakeApplication; -public class HomeControllerTest extends WithApplication { - @Rule - public ExpectedException exceptionGrabber = ExpectedException.none(); +public class HomeControllerTest { + + @RegisterExtension + static ApplicationExtension appExtension = new ApplicationExtension(fakeApplication()); + static Application app = appExtension.getApplication(); + static Materializer mat = appExtension.getMaterializer(); @Test - public void testOnlyFormDataNoFiles() throws ExecutionException, InterruptedException, TimeoutException { + void testOnlyFormDataNoFiles() throws ExecutionException, InterruptedException, TimeoutException { final Map postParams = new HashMap<>(); postParams.put("key1", new String[]{"value1"}); Http.RequestBuilder request = new Http.RequestBuilder() @@ -46,43 +52,45 @@ public void testOnlyFormDataNoFiles() throws ExecutionException, InterruptedExce } @Test - public void testStringFilePart() throws ExecutionException, InterruptedException, TimeoutException { + void testStringFilePart() throws ExecutionException, InterruptedException, TimeoutException { String content = "Twas brillig and the slithy Toves..."; testTemporaryFile(List.of(new Http.MultipartFormData.FilePart<>("document", "jabberwocky.txt", "text/plain", content, data -> Optional.of(ByteString.fromString(data))))); } @Test - public void testStringFilePartToRefToBytesDefined() throws ExecutionException, InterruptedException, TimeoutException { - exceptionGrabber.expect(RuntimeException.class); - exceptionGrabber.expectMessage("To be able to convert this FilePart's ref to bytes you need to define refToBytes of FilePart[java.lang.String]"); + void testStringFilePartToRefToBytesDefined() throws ExecutionException, InterruptedException, TimeoutException { String content = "Twas brillig and the slithy Toves..."; - testTemporaryFile(List.of(new Http.MultipartFormData.FilePart<>("document", "jabberwocky.txt", "text/plain", content))); + assertThrows( + RuntimeException.class, + () -> testTemporaryFile(List.of(new Http.MultipartFormData.FilePart<>("document", "jabberwocky.txt", "text/plain", content))), + "To be able to convert this FilePart's ref to bytes you need to define refToBytes of FilePart[java.lang.String]" + ); } @Test - public void testJavaTemporaryFile() throws IOException, ExecutionException, InterruptedException, TimeoutException { + void testJavaTemporaryFile() throws IOException, ExecutionException, InterruptedException, TimeoutException { Files.TemporaryFile tempFile = Files.singletonTemporaryFileCreator().create("temp", "txt"); write(tempFile.path(), "Twas brillig and the slithy Toves...".getBytes()); testTemporaryFile(List.of(new Http.MultipartFormData.FilePart<>("document", "jabberwocky.txt", "text/plain", tempFile))); } @Test - public void testScalaTemporaryFile() throws IOException, ExecutionException, InterruptedException, TimeoutException { + void testScalaTemporaryFile() throws IOException, ExecutionException, InterruptedException, TimeoutException { play.api.libs.Files.TemporaryFile tempFile = play.api.libs.Files.SingletonTemporaryFileCreator$.MODULE$.create("temp", "txt"); write(tempFile.path(), "Twas brillig and the slithy Toves...".getBytes()); testTemporaryFile(List.of(new Http.MultipartFormData.FilePart<>("document", "jabberwocky.txt", "text/plain", tempFile))); } @Test - public void testFile() throws IOException, ExecutionException, InterruptedException, TimeoutException { + void testFile() throws IOException, ExecutionException, InterruptedException, TimeoutException { play.api.libs.Files.TemporaryFile tempFile = play.api.libs.Files.SingletonTemporaryFileCreator$.MODULE$.create("temp", "txt"); write(tempFile.path(), "Twas brillig and the slithy Toves...".getBytes()); testTemporaryFile(List.of(new Http.MultipartFormData.FilePart<>("document", "jabberwocky.txt", "text/plain", tempFile.file()))); } @Test - public void testPath() throws IOException, ExecutionException, InterruptedException, TimeoutException { + void testPath() throws IOException, ExecutionException, InterruptedException, TimeoutException { play.api.libs.Files.TemporaryFile tempFile = play.api.libs.Files.SingletonTemporaryFileCreator$.MODULE$.create("temp", "txt"); write(tempFile.path(), "Twas brillig and the slithy Toves...".getBytes()); testTemporaryFile(List.of(new Http.MultipartFormData.FilePart<>("document", "jabberwocky.txt", "text/plain", tempFile.path()))); From 0f4304e5534e40a4608210b69f9e7a609afe1a8d Mon Sep 17 00:00:00 2001 From: "H. Habighorst" Date: Sat, 15 Jul 2023 10:12:30 +0200 Subject: [PATCH 13/15] #11839: reduce visibility of methods (public is required only in JUnit 4) --- .../caffeine/NamedCaffeineCacheSpec.java | 10 +-- .../guice/GuiceApplicationBuilderTest.java | 14 +-- .../guice/GuiceApplicationLoaderTest.java | 8 +- .../guice/GuiceInjectorBuilderTest.java | 6 +- .../BuiltInComponentsFromContextTest.java | 54 ++++++------ .../play/it/JavaServerIntegrationTest.java | 11 +-- .../play/routing/AbstractRoutingDslTest.java | 86 +++++++++---------- .../CompileTimeInjectionRoutingDslTest.java | 2 +- .../DependencyInjectedRoutingDslTest.java | 2 +- .../test/java/play/libs/ResourcesTest.java | 8 +- .../src/test/java/play/libs/TimeTest.java | 12 +-- .../src/test/java/play/mvc/HttpTest.java | 18 ++-- .../java/play/mvc/RequestBuilderTest.java | 64 +++++++------- .../play/libs/streams/AccumulatorTest.java | 16 ++-- .../src/test/java/play/core/PathsTest.java | 28 +++--- .../src/test/java/play/i18n/MessagesTest.java | 4 +- .../play/libs/concurrent/FuturesTest.java | 16 ++-- .../play/src/test/java/play/mvc/CallTest.java | 38 ++++---- .../test/java/play/mvc/CookieBuilderTest.java | 10 +-- .../test/java/play/mvc/RangeResultsTest.java | 63 +++++++------- .../src/test/java/play/mvc/ResultsTest.java | 73 ++++++++-------- .../src/test/java/play/mvc/SecurityTest.java | 6 +- .../async/code/javaguide/async/JavaAsync.java | 6 +- .../forms/code/javaguide/forms/JavaForms.java | 2 +- .../javaguide/ws/StandaloneWithConfig.java | 4 +- .../src/test/java/play/db/DatabaseTest.java | 32 +++---- .../test/java/play/db/NamedDatabaseTest.java | 12 +-- .../src/test/java/play/db/jpa/JPAApiTest.java | 30 +++---- .../play/db/evolutions/EvolutionsTest.java | 4 +- .../src/test/java/play/mvc/HttpFormsTest.java | 22 ++--- .../play/data/format/FormattersTest.java | 6 +- 31 files changed, 333 insertions(+), 334 deletions(-) diff --git a/cache/play-caffeine-cache/src/test/java/play/cache/caffeine/NamedCaffeineCacheSpec.java b/cache/play-caffeine-cache/src/test/java/play/cache/caffeine/NamedCaffeineCacheSpec.java index c2433f493cc..14c426c74e7 100644 --- a/cache/play-caffeine-cache/src/test/java/play/cache/caffeine/NamedCaffeineCacheSpec.java +++ b/cache/play-caffeine-cache/src/test/java/play/cache/caffeine/NamedCaffeineCacheSpec.java @@ -14,13 +14,13 @@ import org.junit.jupiter.api.Test; import org.slf4j.LoggerFactory; -public class NamedCaffeineCacheSpec { +class NamedCaffeineCacheSpec { private NamedCaffeineCache cache = new NamedCaffeineCache<>("testNamedCaffeineCache", Caffeine.newBuilder().buildAsync()); @Test - public void getAll_shouldReturnAllValuesWithTheGivenKeys() throws Exception { + void getAll_shouldReturnAllValuesWithTheGivenKeys() throws Exception { String key1 = "key1"; String value1 = "value1"; String key2 = "key2"; @@ -41,7 +41,7 @@ public void getAll_shouldReturnAllValuesWithTheGivenKeys() throws Exception { } @Test - public void getAll_shouldCreateTheMissingValuesAndReturnAllWithTheGivenKeys() throws Exception { + void getAll_shouldCreateTheMissingValuesAndReturnAllWithTheGivenKeys() throws Exception { String key1 = "key1"; String value1 = "value1"; String key2 = "key2"; @@ -63,7 +63,7 @@ public void getAll_shouldCreateTheMissingValuesAndReturnAllWithTheGivenKeys() th } @Test - public void getAll_shouldNotReplaceAlreadyExistingValues() throws Exception { + void getAll_shouldNotReplaceAlreadyExistingValues() throws Exception { String key1 = "key1"; String value1 = "value1"; String key2 = "key2"; @@ -86,7 +86,7 @@ public void getAll_shouldNotReplaceAlreadyExistingValues() throws Exception { } @Test() - public void getAll_shouldReturnFailedFutureIfMappingFunctionIsCompletedExceptionally() { + void getAll_shouldReturnFailedFutureIfMappingFunctionIsCompletedExceptionally() { LoggerFactory.getLogger(NamedCaffeineCache.class); RuntimeException testException = new RuntimeException("test exception"); CompletableFuture> future = new CompletableFuture<>(); diff --git a/core/play-guice/src/test/java/play/inject/guice/GuiceApplicationBuilderTest.java b/core/play-guice/src/test/java/play/inject/guice/GuiceApplicationBuilderTest.java index e7cfa725cf8..b7330528cd0 100644 --- a/core/play-guice/src/test/java/play/inject/guice/GuiceApplicationBuilderTest.java +++ b/core/play-guice/src/test/java/play/inject/guice/GuiceApplicationBuilderTest.java @@ -20,10 +20,10 @@ import play.inject.Injector; import play.libs.Scala; -public class GuiceApplicationBuilderTest { +class GuiceApplicationBuilderTest { @Test - public void addBindings() { + void addBindings() { Injector injector = new GuiceApplicationBuilder() .bindings(new AModule()) @@ -35,7 +35,7 @@ public void addBindings() { } @Test - public void overrideBindings() { + void overrideBindings() { Application app = new GuiceApplicationBuilder() .bindings(new AModule()) @@ -59,14 +59,14 @@ public void overrideBindings() { } @Test - public void disableModules() { + void disableModules() { Injector injector = new GuiceApplicationBuilder().bindings(new AModule()).disable(AModule.class).injector(); assertThrowsExactly(ConfigurationException.class, () -> injector.instanceOf(A.class)); } @Test - public void setInitialConfigurationLoader() { + void setInitialConfigurationLoader() { Config extra = ConfigFactory.parseMap(ImmutableMap.of("a", 1)); Application app = new GuiceApplicationBuilder() @@ -77,7 +77,7 @@ public void setInitialConfigurationLoader() { } @Test - public void setModuleLoader() { + void setModuleLoader() { Injector injector = new GuiceApplicationBuilder() .withModuleLoader( @@ -94,7 +94,7 @@ public void setModuleLoader() { } @Test - public void setLoadedModulesDirectly() { + void setLoadedModulesDirectly() { Injector injector = new GuiceApplicationBuilder() .load( diff --git a/core/play-guice/src/test/java/play/inject/guice/GuiceApplicationLoaderTest.java b/core/play-guice/src/test/java/play/inject/guice/GuiceApplicationLoaderTest.java index 2d58ae83884..71d9ef9abb0 100644 --- a/core/play-guice/src/test/java/play/inject/guice/GuiceApplicationLoaderTest.java +++ b/core/play-guice/src/test/java/play/inject/guice/GuiceApplicationLoaderTest.java @@ -16,14 +16,14 @@ import play.ApplicationLoader; import play.Environment; -public class GuiceApplicationLoaderTest { +class GuiceApplicationLoaderTest { private ApplicationLoader.Context fakeContext() { return ApplicationLoader.create(Environment.simple()); } @Test - public void additionalModulesAndBindings() { + void additionalModulesAndBindings() { GuiceApplicationBuilder builder = new GuiceApplicationBuilder().bindings(new AModule()).bindings(bind(B.class).to(B1.class)); ApplicationLoader loader = new GuiceApplicationLoader(builder); @@ -34,7 +34,7 @@ public void additionalModulesAndBindings() { } @Test - public void extendLoaderAndSetConfiguration() { + void extendLoaderAndSetConfiguration() { ApplicationLoader loader = new GuiceApplicationLoader() { @Override @@ -52,7 +52,7 @@ public GuiceApplicationBuilder builder(Context context) { } @Test - public void usingAdditionalConfiguration() { + void usingAdditionalConfiguration() { Properties properties = new Properties(); properties.setProperty("play.http.context", "/tests"); diff --git a/core/play-guice/src/test/java/play/inject/guice/GuiceInjectorBuilderTest.java b/core/play-guice/src/test/java/play/inject/guice/GuiceInjectorBuilderTest.java index fd8966ff8f7..3559e640bb8 100644 --- a/core/play-guice/src/test/java/play/inject/guice/GuiceInjectorBuilderTest.java +++ b/core/play-guice/src/test/java/play/inject/guice/GuiceInjectorBuilderTest.java @@ -30,7 +30,7 @@ import play.inject.Module; import scala.collection.Seq; -public class GuiceInjectorBuilderTest { +class GuiceInjectorBuilderTest { static Stream environmentTargets() { return Stream.of( @@ -132,7 +132,7 @@ void supportVariousBindings( } @Test - public void overrideBindings() { + void overrideBindings() { Injector injector = new GuiceInjectorBuilder() .bindings(new AModule()) @@ -146,7 +146,7 @@ public void overrideBindings() { } @Test - public void disableModules() { + void disableModules() { Injector injector = new GuiceInjectorBuilder() .bindings(new AModule(), new BModule()) diff --git a/core/play-integration-test/src/it/java/play/BuiltInComponentsFromContextTest.java b/core/play-integration-test/src/it/java/play/BuiltInComponentsFromContextTest.java index feae0d64e08..d15c5db20af 100644 --- a/core/play-integration-test/src/it/java/play/BuiltInComponentsFromContextTest.java +++ b/core/play-integration-test/src/it/java/play/BuiltInComponentsFromContextTest.java @@ -23,7 +23,7 @@ import play.test.Helpers; import scala.Option; -public class BuiltInComponentsFromContextTest { +class BuiltInComponentsFromContextTest { class TestBuiltInComponentsFromContext extends BuiltInComponentsFromContext implements HttpFiltersComponents, BodyParserComponents { @@ -50,7 +50,7 @@ public void initialize() { } @Test - public void shouldProvideAApplication() { + void shouldProvideAApplication() { Application application = componentsFromContext.application(); Helpers.running( application, @@ -62,12 +62,12 @@ public void shouldProvideAApplication() { } @Test - public void shouldProvideDefaultFilters() { + void shouldProvideDefaultFilters() { assertFalse(this.componentsFromContext.httpFilters().isEmpty()); } @Test - public void shouldProvideRouter() { + void shouldProvideRouter() { Router router = this.componentsFromContext.router(); assertNotNull(router); @@ -79,7 +79,7 @@ public void shouldProvideRouter() { } @Test - public void shouldProvideHttpConfiguration() { + void shouldProvideHttpConfiguration() { HttpConfiguration httpConfiguration = this.componentsFromContext.httpConfiguration(); assertNotNull(httpConfiguration); assertEquals("/", httpConfiguration.context()); @@ -88,118 +88,118 @@ public void shouldProvideHttpConfiguration() { // The tests below just ensure that the we are able to instantiate the components @Test - public void shouldProvideApplicationLifecycle() { + void shouldProvideApplicationLifecycle() { assertNotNull(this.componentsFromContext.applicationLifecycle()); } @Test - public void shouldProvideActionCreator() { + void shouldProvideActionCreator() { assertNotNull(this.componentsFromContext.actionCreator()); } @Test - public void shouldProvideAkkActorSystem() { + void shouldProvideAkkActorSystem() { assertNotNull(this.componentsFromContext.actorSystem()); } @Test - public void shouldProvideAkkaMaterializer() { + void shouldProvideAkkaMaterializer() { assertNotNull(this.componentsFromContext.materializer()); } @Test - public void shouldProvideExecutionContext() { + void shouldProvideExecutionContext() { assertNotNull(this.componentsFromContext.executionContext()); } @Test - public void shouldProvideCookieSigner() { + void shouldProvideCookieSigner() { assertNotNull(this.componentsFromContext.cookieSigner()); } @Test - public void shouldProvideCSRFTokenSigner() { + void shouldProvideCSRFTokenSigner() { assertNotNull(this.componentsFromContext.csrfTokenSigner()); } @Test - public void shouldProvideFileMimeTypes() { + void shouldProvideFileMimeTypes() { assertNotNull(this.componentsFromContext.fileMimeTypes()); } @Test - public void shouldProvideHttpErrorHandler() { + void shouldProvideHttpErrorHandler() { assertNotNull(this.componentsFromContext.httpErrorHandler()); } @Test - public void shouldProvideHttpRequestHandler() { + void shouldProvideHttpRequestHandler() { assertNotNull(this.componentsFromContext.httpRequestHandler()); } @Test - public void shouldProvideLangs() { + void shouldProvideLangs() { assertNotNull(this.componentsFromContext.langs()); } @Test - public void shouldProvideMessagesApi() { + void shouldProvideMessagesApi() { assertNotNull(this.componentsFromContext.messagesApi()); } @Test - public void shouldProvideTempFileCreator() { + void shouldProvideTempFileCreator() { assertNotNull(this.componentsFromContext.tempFileCreator()); } @Test - public void actorSystemMustBeASingleton() { + void actorSystemMustBeASingleton() { assertSame(this.componentsFromContext.actorSystem(), this.componentsFromContext.actorSystem()); } @Test - public void applicationMustBeASingleton() { + void applicationMustBeASingleton() { assertSame(this.componentsFromContext.application(), this.componentsFromContext.application()); } @Test - public void langsMustBeASingleton() { + void langsMustBeASingleton() { assertSame(this.componentsFromContext.langs(), this.componentsFromContext.langs()); } @Test - public void fileMimeTypesMustBeASingleton() { + void fileMimeTypesMustBeASingleton() { assertSame( this.componentsFromContext.fileMimeTypes(), this.componentsFromContext.fileMimeTypes()); } @Test - public void httpRequestHandlerMustBeASingleton() { + void httpRequestHandlerMustBeASingleton() { assertSame( this.componentsFromContext.httpRequestHandler(), this.componentsFromContext.httpRequestHandler()); } @Test - public void cookieSignerMustBeASingleton() { + void cookieSignerMustBeASingleton() { assertSame( this.componentsFromContext.cookieSigner(), this.componentsFromContext.cookieSigner()); } @Test - public void csrfTokenSignerMustBeASingleton() { + void csrfTokenSignerMustBeASingleton() { assertSame( this.componentsFromContext.csrfTokenSigner(), this.componentsFromContext.csrfTokenSigner()); } @Test - public void temporaryFileCreatorMustBeASingleton() { + void temporaryFileCreatorMustBeASingleton() { assertSame( this.componentsFromContext.tempFileCreator(), this.componentsFromContext.tempFileCreator()); } @Test - public void shouldKeepStateForWebCommands() { + void shouldKeepStateForWebCommands() { componentsFromContext .webCommands() .addHandler( diff --git a/core/play-integration-test/src/it/java/play/it/JavaServerIntegrationTest.java b/core/play-integration-test/src/it/java/play/it/JavaServerIntegrationTest.java index ad877e55ab0..5c6b2c399c9 100644 --- a/core/play-integration-test/src/it/java/play/it/JavaServerIntegrationTest.java +++ b/core/play-integration-test/src/it/java/play/it/JavaServerIntegrationTest.java @@ -21,9 +21,10 @@ import play.routing.Router; import play.server.Server; -public class JavaServerIntegrationTest { +class JavaServerIntegrationTest { + @Test - public void testHttpEmbeddedServerUsesCorrectProtocolAndPort() throws Exception { + void testHttpEmbeddedServerUsesCorrectProtocolAndPort() throws Exception { int port = _availablePort(); _running( new Server.Builder().http(port).build(_emptyRouter()), @@ -41,7 +42,7 @@ public void testHttpEmbeddedServerUsesCorrectProtocolAndPort() throws Exception } @Test - public void testHttpsEmbeddedServerUsesCorrectProtocolAndPort() throws Exception { + void testHttpsEmbeddedServerUsesCorrectProtocolAndPort() throws Exception { int port = _availablePort(); _running( new Server.Builder().https(port).build(_emptyRouter()), @@ -58,7 +59,7 @@ public void testHttpsEmbeddedServerUsesCorrectProtocolAndPort() throws Exception } @Test - public void testEmbeddedServerCanServeBothProtocolsSimultaneously() throws Exception { + void testEmbeddedServerCanServeBothProtocolsSimultaneously() throws Exception { List availablePorts = _availablePorts(2); int httpPort = availablePorts.get(0); int httpsPort = availablePorts.get(1); @@ -82,7 +83,7 @@ public void testEmbeddedServerCanServeBothProtocolsSimultaneously() throws Excep } @Test - public void testEmbeddedServerWillChooseAnHTTPPortIfNotProvided() throws Exception { + void testEmbeddedServerWillChooseAnHTTPPortIfNotProvided() throws Exception { _running( new Server.Builder().build(_emptyRouter()), server -> { diff --git a/core/play-integration-test/src/it/java/play/routing/AbstractRoutingDslTest.java b/core/play-integration-test/src/it/java/play/routing/AbstractRoutingDslTest.java index e947199faf5..d15ef9cbc33 100644 --- a/core/play-integration-test/src/it/java/play/routing/AbstractRoutingDslTest.java +++ b/core/play-integration-test/src/it/java/play/routing/AbstractRoutingDslTest.java @@ -32,7 +32,7 @@ * This class is in the integration tests so that we have the right helper classes to build a * request with to test it. */ -public abstract class AbstractRoutingDslTest { +abstract class AbstractRoutingDslTest { abstract Application application(); @@ -43,7 +43,7 @@ private Router router(Function function) { } @Test - public void shouldProvideJavaRequestToActionWithoutParameters() { + void shouldProvideJavaRequestToActionWithoutParameters() { Router router = router( routingDsl -> @@ -60,7 +60,7 @@ public void shouldProvideJavaRequestToActionWithoutParameters() { } @Test - public void shouldProvideJavaRequestToActionWithSingleParameter() { + void shouldProvideJavaRequestToActionWithSingleParameter() { Router router = router( routingDsl -> @@ -80,7 +80,7 @@ public void shouldProvideJavaRequestToActionWithSingleParameter() { } @Test - public void shouldProvideJavaRequestToActionWith2Parameters() { + void shouldProvideJavaRequestToActionWith2Parameters() { Router router = router( routingDsl -> @@ -101,7 +101,7 @@ public void shouldProvideJavaRequestToActionWith2Parameters() { } @Test - public void shouldProvideJavaRequestToActionWith3Parameters() { + void shouldProvideJavaRequestToActionWith3Parameters() { Router router = router( routingDsl -> @@ -124,7 +124,7 @@ public void shouldProvideJavaRequestToActionWith3Parameters() { } @Test - public void shouldProvideJavaRequestToAsyncActionWithoutParameters() { + void shouldProvideJavaRequestToAsyncActionWithoutParameters() { Router router = router( routingDsl -> @@ -145,7 +145,7 @@ public void shouldProvideJavaRequestToAsyncActionWithoutParameters() { } @Test - public void shouldProvideJavaRequestToAsyncActionWithSingleParameter() { + void shouldProvideJavaRequestToAsyncActionWithSingleParameter() { Router router = router( routingDsl -> @@ -166,7 +166,7 @@ public void shouldProvideJavaRequestToAsyncActionWithSingleParameter() { } @Test - public void shouldProvideJavaRequestToAsyncActionWith2Parameters() { + void shouldProvideJavaRequestToAsyncActionWith2Parameters() { Router router = router( routingDsl -> @@ -188,7 +188,7 @@ public void shouldProvideJavaRequestToAsyncActionWith2Parameters() { } @Test - public void shouldProvideJavaRequestToAsyncActionWith3Parameters() { + void shouldProvideJavaRequestToAsyncActionWith3Parameters() { Router router = router( routingDsl -> @@ -213,7 +213,7 @@ public void shouldProvideJavaRequestToAsyncActionWith3Parameters() { } @Test - public void shouldPreserveRequestBodyAsText() { + void shouldPreserveRequestBodyAsText() { Router router = router( routingDsl -> @@ -227,7 +227,7 @@ public void shouldPreserveRequestBodyAsText() { } @Test - public void shouldPreserveRequestBodyAsJson() { + void shouldPreserveRequestBodyAsJson() { Router router = router( routingDsl -> @@ -246,7 +246,7 @@ public void shouldPreserveRequestBodyAsJson() { } @Test - public void shouldPreserveRequestBodyAsXml() { + void shouldPreserveRequestBodyAsXml() { Router router = router( routingDsl -> @@ -267,7 +267,7 @@ public void shouldPreserveRequestBodyAsXml() { } @Test - public void shouldPreserveRequestBodyAsRawBuffer() { + void shouldPreserveRequestBodyAsRawBuffer() { Router router = router( routingDsl -> @@ -286,7 +286,7 @@ public void shouldPreserveRequestBodyAsRawBuffer() { } @Test - public void shouldAcceptMultipartFormData() throws IOException { + void shouldAcceptMultipartFormData() throws IOException { Router router = router( routingDsl -> @@ -342,7 +342,7 @@ public void shouldAcceptMultipartFormData() throws IOException { } @Test - public void shouldPreserveRequestBodyAsTextWhenUsingHttpRequest() { + void shouldPreserveRequestBodyAsTextWhenUsingHttpRequest() { Router router = router( routingDsl -> @@ -353,7 +353,7 @@ public void shouldPreserveRequestBodyAsTextWhenUsingHttpRequest() { } @Test - public void shouldPreserveRequestBodyAsJsonWhenUsingHttpRequest() { + void shouldPreserveRequestBodyAsJsonWhenUsingHttpRequest() { Router router = router( routingDsl -> @@ -369,7 +369,7 @@ public void shouldPreserveRequestBodyAsJsonWhenUsingHttpRequest() { } @Test - public void shouldPreserveRequestBodyAsXmlWhenUsingHttpRequest() { + void shouldPreserveRequestBodyAsXmlWhenUsingHttpRequest() { Router router = router( routingDsl -> @@ -390,7 +390,7 @@ public void shouldPreserveRequestBodyAsXmlWhenUsingHttpRequest() { } @Test - public void shouldPreserveRequestBodyAsRawBufferWhenUsingHttpRequest() { + void shouldPreserveRequestBodyAsRawBufferWhenUsingHttpRequest() { Router router = router( routingDsl -> @@ -409,7 +409,7 @@ public void shouldPreserveRequestBodyAsRawBufferWhenUsingHttpRequest() { } @Test - public void noParameters() { + void noParameters() { Router router = router( routingDsl -> @@ -420,7 +420,7 @@ public void noParameters() { } @Test - public void oneParameter() { + void oneParameter() { Router router = router( routingDsl -> @@ -431,7 +431,7 @@ public void oneParameter() { } @Test - public void twoParameters() { + void twoParameters() { Router router = router( routingDsl -> @@ -445,7 +445,7 @@ public void twoParameters() { } @Test - public void threeParameters() { + void threeParameters() { Router router = router( routingDsl -> @@ -459,7 +459,7 @@ public void threeParameters() { } @Test - public void noParametersAsync() { + void noParametersAsync() { Router router = router( routingDsl -> @@ -473,7 +473,7 @@ public void noParametersAsync() { } @Test - public void oneParameterAsync() { + void oneParameterAsync() { Router router = router( routingDsl -> @@ -487,7 +487,7 @@ public void oneParameterAsync() { } @Test - public void twoParametersAsync() { + void twoParametersAsync() { Router router = router( routingDsl -> @@ -501,7 +501,7 @@ public void twoParametersAsync() { } @Test - public void threeParametersAsync() { + void threeParametersAsync() { Router router = router( routingDsl -> @@ -516,7 +516,7 @@ public void threeParametersAsync() { } @Test - public void get() { + void get() { Router router = router( routingDsl -> @@ -527,7 +527,7 @@ public void get() { } @Test - public void head() { + void head() { Router router = router( routingDsl -> @@ -538,7 +538,7 @@ public void head() { } @Test - public void post() { + void post() { Router router = router( routingDsl -> @@ -549,7 +549,7 @@ public void post() { } @Test - public void put() { + void put() { Router router = router( routingDsl -> @@ -560,7 +560,7 @@ public void put() { } @Test - public void delete() { + void delete() { Router router = router( routingDsl -> @@ -571,7 +571,7 @@ public void delete() { } @Test - public void patch() { + void patch() { Router router = router( routingDsl -> @@ -582,7 +582,7 @@ public void patch() { } @Test - public void options() { + void options() { Router router = router( routingDsl -> @@ -593,7 +593,7 @@ public void options() { } @Test - public void withSessionAndHeader() { + void withSessionAndHeader() { Router router = router( routingDsl -> @@ -612,7 +612,7 @@ public void withSessionAndHeader() { } @Test - public void starMatcher() { + void starMatcher() { Router router = router( routingDsl -> @@ -623,7 +623,7 @@ public void starMatcher() { } @Test - public void regexMatcher() { + void regexMatcher() { Router router = router( routingDsl -> @@ -637,7 +637,7 @@ public void regexMatcher() { } @Test - public void multipleRoutes() { + void multipleRoutes() { Router router = router( routingDsl -> @@ -659,7 +659,7 @@ public void multipleRoutes() { } @Test - public void encoding() { + void encoding() { Router router = router( routingDsl -> @@ -678,7 +678,7 @@ public void encoding() { } @Test - public void typed() { + void typed() { Router router = router( routingDsl -> @@ -693,21 +693,21 @@ public void typed() { } @Test - public void wrongNumberOfParameters() { + void wrongNumberOfParameters() { assertThrowsExactly( IllegalArgumentException.class, () -> routingDsl().GET("/:a/:b").routingTo((req, foo) -> ok(foo.toString()))); } @Test - public void badParameterType() { + void badParameterType() { assertThrowsExactly( IllegalArgumentException.class, () -> routingDsl().GET("/:a").routingTo((Http.Request req, InputStream is) -> ok())); } @Test - public void bindError() { + void bindError() { Router router = router( routingDsl -> @@ -722,7 +722,7 @@ public void bindError() { } @Test - public void customPathBindable() { + void customPathBindable() { Router router = router( routingDsl -> diff --git a/core/play-integration-test/src/it/java/play/routing/CompileTimeInjectionRoutingDslTest.java b/core/play-integration-test/src/it/java/play/routing/CompileTimeInjectionRoutingDslTest.java index 759c7e3e8fa..54e4c613674 100644 --- a/core/play-integration-test/src/it/java/play/routing/CompileTimeInjectionRoutingDslTest.java +++ b/core/play-integration-test/src/it/java/play/routing/CompileTimeInjectionRoutingDslTest.java @@ -9,7 +9,7 @@ import play.ApplicationLoader; import play.filters.components.NoHttpFiltersComponents; -public class CompileTimeInjectionRoutingDslTest extends AbstractRoutingDslTest { +class CompileTimeInjectionRoutingDslTest extends AbstractRoutingDslTest { private static TestComponents components; private static Application application; diff --git a/core/play-integration-test/src/it/java/play/routing/DependencyInjectedRoutingDslTest.java b/core/play-integration-test/src/it/java/play/routing/DependencyInjectedRoutingDslTest.java index 57d3a2a7549..4d8ba8d3eb0 100644 --- a/core/play-integration-test/src/it/java/play/routing/DependencyInjectedRoutingDslTest.java +++ b/core/play-integration-test/src/it/java/play/routing/DependencyInjectedRoutingDslTest.java @@ -10,7 +10,7 @@ import play.inject.guice.GuiceApplicationBuilder; import play.test.Helpers; -public class DependencyInjectedRoutingDslTest extends AbstractRoutingDslTest { +class DependencyInjectedRoutingDslTest extends AbstractRoutingDslTest { private static Application app; diff --git a/core/play-java/src/test/java/play/libs/ResourcesTest.java b/core/play-java/src/test/java/play/libs/ResourcesTest.java index b7a5d5e51d0..a8193c67c17 100644 --- a/core/play-java/src/test/java/play/libs/ResourcesTest.java +++ b/core/play-java/src/test/java/play/libs/ResourcesTest.java @@ -14,10 +14,10 @@ import java.util.concurrent.ExecutionException; import org.junit.jupiter.api.Test; -public class ResourcesTest { +class ResourcesTest { @Test - public void testAsyncTryWithResource() throws Exception { + void testAsyncTryWithResource() throws Exception { InputStream inputStream = mock(InputStream.class); CompletionStage completionStage = @@ -28,7 +28,7 @@ public void testAsyncTryWithResource() throws Exception { } @Test - public void testAsyncTryWithResourceExceptionInFuture() throws Exception { + void testAsyncTryWithResourceExceptionInFuture() throws Exception { InputStream inputStream = mock(InputStream.class); CompletionStage completionStage = Resources.asyncTryWithResource( @@ -50,7 +50,7 @@ public void testAsyncTryWithResourceExceptionInFuture() throws Exception { } @Test - public void testAsyncTryWithResourceException() throws Exception { + void testAsyncTryWithResourceException() throws Exception { InputStream inputStream = mock(InputStream.class); try { CompletionStage completionStage = diff --git a/core/play-java/src/test/java/play/libs/TimeTest.java b/core/play-java/src/test/java/play/libs/TimeTest.java index a77e5cc1d7d..fcef80eb1bf 100644 --- a/core/play-java/src/test/java/play/libs/TimeTest.java +++ b/core/play-java/src/test/java/play/libs/TimeTest.java @@ -9,7 +9,7 @@ import org.junit.jupiter.api.Test; -public class TimeTest { +class TimeTest { static final int oneSecond = 1; static final int oneMinute = 60; @@ -18,13 +18,13 @@ public class TimeTest { static final int thirtyDays = oneDay * 30; @Test - public void testDefaultTime() { + void testDefaultTime() { int result = Time.parseDuration(null); assertEquals(thirtyDays, result); } @Test - public void testSeconds() { + void testSeconds() { int result1 = Time.parseDuration("1s"); assertEquals(oneSecond, result1); @@ -47,7 +47,7 @@ public void testSeconds() { } @Test - public void testMinutes() { + void testMinutes() { int result1 = Time.parseDuration("1mn"); assertEquals(oneMinute, result1); @@ -83,7 +83,7 @@ public void testMinutes() { } @Test - public void testHours() { + void testHours() { int result1 = Time.parseDuration("1h"); assertEquals(oneHour, result1); @@ -106,7 +106,7 @@ public void testHours() { } @Test - public void testDays() { + void testDays() { int result1 = Time.parseDuration("1d"); assertEquals(oneDay, result1); diff --git a/core/play-java/src/test/java/play/mvc/HttpTest.java b/core/play-java/src/test/java/play/mvc/HttpTest.java index 7f04831fcab..f7634d8b5fd 100644 --- a/core/play-java/src/test/java/play/mvc/HttpTest.java +++ b/core/play-java/src/test/java/play/mvc/HttpTest.java @@ -26,7 +26,7 @@ * Tests for the Http class. This test is in the play-java project because we want to use some of * the play-java classes, e.g. the GuiceApplicationBuilder. */ -public class HttpTest { +class HttpTest { /** Gets the PLAY_LANG cookie, or the last one if there is more than one */ private String resultLangCookie(Result result, MessagesApi messagesApi) { @@ -61,7 +61,7 @@ private static void withApplication(Consumer r) { } @Test - public void testChangeLang() { + void testChangeLang() { withApplication( (app) -> { // Start off as 'en' with no cookie set @@ -82,7 +82,7 @@ public void testChangeLang() { } @Test - public void testMessagesOrder() { + void testMessagesOrder() { withApplication( (app) -> { RequestBuilder rb = new RequestBuilder().header(ACCEPT_LANGUAGE, "en-US"); @@ -104,7 +104,7 @@ public void testMessagesOrder() { } @Test - public void testChangeLangFailure() { + void testChangeLangFailure() { withApplication( (app) -> { // Start off as 'en' with no cookie set @@ -123,7 +123,7 @@ public void testChangeLangFailure() { } @Test - public void testClearLang() { + void testClearLang() { withApplication( (app) -> { // Set 'fr' as our initial language @@ -142,7 +142,7 @@ public void testClearLang() { } @Test - public void testSetTransientLang() { + void testSetTransientLang() { withApplication( (app) -> { Request req = new RequestBuilder().build(); @@ -161,7 +161,7 @@ public void testSetTransientLang() { } @Test - public void testSetTransientLangFailure() { + void testSetTransientLangFailure() { withApplication( (app) -> { Request req = new RequestBuilder().build(); @@ -179,7 +179,7 @@ public void testSetTransientLangFailure() { } @Test - public void testClearTransientLang() { + void testClearTransientLang() { withApplication( (app) -> { Lang lang = Lang.forCode("fr"); @@ -206,7 +206,7 @@ public void testClearTransientLang() { } @Test - public void testRequestImplLang() { + void testRequestImplLang() { withApplication( (app) -> { RequestBuilder rb = new RequestBuilder(); diff --git a/core/play-java/src/test/java/play/mvc/RequestBuilderTest.java b/core/play-java/src/test/java/play/mvc/RequestBuilderTest.java index efd9b1ab79e..3a325290be3 100644 --- a/core/play-java/src/test/java/play/mvc/RequestBuilderTest.java +++ b/core/play-java/src/test/java/play/mvc/RequestBuilderTest.java @@ -33,34 +33,34 @@ import play.mvc.Http.RequestBuilder; import play.test.Helpers; -public class RequestBuilderTest { +class RequestBuilderTest { @Test - public void testUri_absolute() { + void testUri_absolute() { Request request = new RequestBuilder().uri("https://www.benmccann.com/blog").build(); assertEquals("https://www.benmccann.com/blog", request.uri()); } @Test - public void testUri_relative() { + void testUri_relative() { Request request = new RequestBuilder().uri("/blog").build(); assertEquals("/blog", request.uri()); } @Test - public void testUri_asterisk() { + void testUri_asterisk() { Request request = new RequestBuilder().method("OPTIONS").uri("*").build(); assertEquals("*", request.uri()); } @Test - public void testSecure() { + void testSecure() { assertFalse(new RequestBuilder().uri("http://www.benmccann.com/blog").build().secure()); assertTrue(new RequestBuilder().uri("https://www.benmccann.com/blog").build().secure()); } @Test - public void testAttrs() { + void testAttrs() { final TypedKey NUMBER = TypedKey.create("number"); final TypedKey COLOR = TypedKey.create("color"); @@ -128,7 +128,7 @@ public void testAttrs() { } @Test - public void testNewRequestsShouldNotHaveATransientLang() { + void testNewRequestsShouldNotHaveATransientLang() { RequestBuilder builder = new RequestBuilder().uri("http://www.playframework.com/"); Request request = builder.build(); @@ -137,7 +137,7 @@ public void testNewRequestsShouldNotHaveATransientLang() { } @Test - public void testAddATransientLangToRequest() { + void testAddATransientLangToRequest() { RequestBuilder builder = new RequestBuilder().uri("http://www.playframework.com/"); Lang lang = new Lang(Locale.GERMAN); @@ -148,7 +148,7 @@ public void testAddATransientLangToRequest() { } @Test - public void testAddATransientLangByCodeToRequest() { + void testAddATransientLangByCodeToRequest() { RequestBuilder builder = new RequestBuilder().uri("http://www.playframework.com/"); String lang = "de"; @@ -159,7 +159,7 @@ public void testAddATransientLangByCodeToRequest() { } @Test - public void testAddATransientLangByLocaleToRequest() { + void testAddATransientLangByLocaleToRequest() { RequestBuilder builder = new RequestBuilder().uri("http://www.playframework.com/"); Locale locale = Locale.GERMAN; @@ -170,7 +170,7 @@ public void testAddATransientLangByLocaleToRequest() { } @Test - public void testClearRequestTransientLang() { + void testClearRequestTransientLang() { RequestBuilder builder = new RequestBuilder().uri("http://www.playframework.com/"); Lang lang = new Lang(Locale.GERMAN); @@ -182,7 +182,7 @@ public void testClearRequestTransientLang() { } @Test - public void testAddATransientLangToRequestBuilder() { + void testAddATransientLangToRequestBuilder() { RequestBuilder builder = new RequestBuilder().uri("http://www.playframework.com/"); Lang lang = new Lang(Locale.GERMAN); @@ -193,7 +193,7 @@ public void testAddATransientLangToRequestBuilder() { } @Test - public void testAddATransientLangByCodeToRequestBuilder() { + void testAddATransientLangByCodeToRequestBuilder() { RequestBuilder builder = new RequestBuilder().uri("http://www.playframework.com/"); String lang = "de"; @@ -204,7 +204,7 @@ public void testAddATransientLangByCodeToRequestBuilder() { } @Test - public void testAddATransientLangByLocaleToRequestBuilder() { + void testAddATransientLangByLocaleToRequestBuilder() { RequestBuilder builder = new RequestBuilder().uri("http://www.playframework.com/"); Locale locale = Locale.GERMAN; @@ -215,7 +215,7 @@ public void testAddATransientLangByLocaleToRequestBuilder() { } @Test - public void testClearRequestBuilderTransientLang() { + void testClearRequestBuilderTransientLang() { Lang lang = new Lang(Locale.GERMAN); RequestBuilder builder = new RequestBuilder().uri("http://www.playframework.com/").transientLang(lang); @@ -228,7 +228,7 @@ public void testClearRequestBuilderTransientLang() { } @Test - public void testNewRequestsShouldNotHaveALangCookie() { + void testNewRequestsShouldNotHaveALangCookie() { RequestBuilder builder = new RequestBuilder().uri("http://www.playframework.com/"); Request request = builder.build(); @@ -238,7 +238,7 @@ public void testNewRequestsShouldNotHaveALangCookie() { } @Test - public void testAddALangCookieToRequestBuilder() { + void testAddALangCookieToRequestBuilder() { RequestBuilder builder = new RequestBuilder().uri("http://www.playframework.com/"); Lang lang = new Lang(Locale.GERMAN); @@ -252,7 +252,7 @@ public void testAddALangCookieToRequestBuilder() { } @Test - public void testAddALangCookieByLocaleToRequestBuilder() { + void testAddALangCookieByLocaleToRequestBuilder() { RequestBuilder builder = new RequestBuilder().uri("http://www.playframework.com/"); Locale locale = Locale.GERMAN; @@ -266,7 +266,7 @@ public void testAddALangCookieByLocaleToRequestBuilder() { } @Test - public void testFlash() { + void testFlash() { final Request req = new RequestBuilder().flash("a", "1").flash("b", "1").flash("b", "2").build(); assertEquals(Optional.of("1"), req.flash().get("a")); @@ -274,7 +274,7 @@ public void testFlash() { } @Test - public void testSession() { + void testSession() { final Request req = new RequestBuilder().session("a", "1").session("b", "1").session("b", "2").build(); assertEquals(Optional.of("1"), req.session().get("a")); @@ -282,7 +282,7 @@ public void testSession() { } @Test - public void testUsername() { + void testUsername() { final Request req1 = new RequestBuilder().uri("http://playframework.com/").build(); final Request req2 = req1.addAttr(Security.USERNAME, "user2"); final Request req3 = req1.addAttr(Security.USERNAME, "user3"); @@ -305,49 +305,49 @@ public void testUsername() { } @Test - public void testGetQuery_doubleEncoding() { + void testGetQuery_doubleEncoding() { final Optional query = new Http.RequestBuilder().uri("path?query=x%2By").build().queryString("query"); assertEquals(Optional.of("x+y"), query); } @Test - public void testQuery_doubleEncoding() { + void testQuery_doubleEncoding() { final Optional query = new Http.RequestBuilder().uri("path?query=x%2By").build().queryString("query"); assertEquals(Optional.of("x+y"), query); } @Test - public void testGetQuery_multipleParams() { + void testGetQuery_multipleParams() { final Request req = new Http.RequestBuilder().uri("/path?one=1&two=a+b&").build(); assertEquals(Optional.of("1"), req.queryString("one")); assertEquals(Optional.of("a b"), req.queryString("two")); } @Test - public void testQuery_multipleParams() { + void testQuery_multipleParams() { final Request req = new Http.RequestBuilder().uri("/path?one=1&two=a+b&").build(); assertEquals(Optional.of("1"), req.queryString("one")); assertEquals(Optional.of("a b"), req.queryString("two")); } @Test - public void testGetQuery_emptyParam() { + void testGetQuery_emptyParam() { final Request req = new Http.RequestBuilder().uri("/path?one=&two=a+b&").build(); assertEquals(Optional.empty(), req.queryString("one")); assertEquals(Optional.of("a b"), req.queryString("two")); } @Test - public void testQuery_emptyParam() { + void testQuery_emptyParam() { final Request req = new Http.RequestBuilder().uri("/path?one=&two=a+b&").build(); assertEquals(Optional.empty(), req.queryString("one")); assertEquals(Optional.of("a b"), req.queryString("two")); } @Test - public void testGetUri_badEncoding() { + void testGetUri_badEncoding() { final Request req = new Http.RequestBuilder().uri("/test.html?one=hello=world&two=false").build(); assertEquals(Optional.of("hello=world"), req.queryString("one")); @@ -355,7 +355,7 @@ public void testGetUri_badEncoding() { } @Test - public void testUri_badEncoding() { + void testUri_badEncoding() { final Request req = new Http.RequestBuilder().uri("/test.html?one=hello=world&two=false").build(); assertEquals(Optional.of("hello=world"), req.queryString("one")); @@ -363,7 +363,7 @@ public void testUri_badEncoding() { } @Test - public void multipartForm() throws ExecutionException, InterruptedException { + void multipartForm() throws ExecutionException, InterruptedException { Application app = new GuiceApplicationBuilder().build(); Play.start(app); TemporaryFileCreator temporaryFileCreator = @@ -390,7 +390,7 @@ public void multipartForm() throws ExecutionException, InterruptedException { } @Test - public void multipartForm_bodyRaw_correctEscapedParams() throws URISyntaxException, IOException { + void multipartForm_bodyRaw_correctEscapedParams() throws URISyntaxException, IOException { Application app = new GuiceApplicationBuilder().build(); Play.start(app); @@ -432,7 +432,7 @@ public void multipartForm_bodyRaw_correctEscapedParams() throws URISyntaxExcepti } @Test - public void multipartFormContentLength() { + void multipartFormContentLength() { final Map dataParts = new HashMap<>(); dataParts.put("f\ni\re\"l\nd1", new String[] {"value1"}); dataParts.put("field2", new String[] {"value2-1", "value2.2"}); diff --git a/core/play-streams/src/test/java/play/libs/streams/AccumulatorTest.java b/core/play-streams/src/test/java/play/libs/streams/AccumulatorTest.java index c1773a7e41f..173c7dfb408 100644 --- a/core/play-streams/src/test/java/play/libs/streams/AccumulatorTest.java +++ b/core/play-streams/src/test/java/play/libs/streams/AccumulatorTest.java @@ -21,7 +21,7 @@ import org.junit.jupiter.api.Test; import org.reactivestreams.Subscription; -public class AccumulatorTest { +class AccumulatorTest { private Materializer mat; private ActorSystem system; @@ -56,12 +56,12 @@ public void cancel() {} } @Test - public void map() throws Exception { + void map() throws Exception { assertEquals(16, (int) await(sum.map(s -> s + 10, ec).run(source, mat))); } @Test - public void mapFuture() throws Exception { + void mapFuture() throws Exception { assertEquals( 16, (int) @@ -71,17 +71,17 @@ public void mapFuture() throws Exception { } @Test - public void recoverMaterializedException() throws Exception { + void recoverMaterializedException() throws Exception { assertEquals(20, (int) await(sum.map(this.error(), ec).recover(t -> 20, ec).run(source, mat))); } @Test - public void recoverStreamException() throws Exception { + void recoverStreamException() throws Exception { assertEquals(20, (int) await(sum.recover(t -> 20, ec).run(errorSource(), mat))); } @Test - public void recoverWithMaterializedException() throws Exception { + void recoverWithMaterializedException() throws Exception { assertEquals( 20, (int) @@ -92,7 +92,7 @@ public void recoverWithMaterializedException() throws Exception { } @Test - public void recoverWithStreamException() throws Exception { + void recoverWithStreamException() throws Exception { assertEquals( 20, (int) @@ -102,7 +102,7 @@ public void recoverWithStreamException() throws Exception { } @Test - public void through() throws Exception { + void through() throws Exception { assertEquals( 12, (int) await(sum.through(Flow.create().map(i -> i * 2)).run(source, mat))); } diff --git a/core/play/src/test/java/play/core/PathsTest.java b/core/play/src/test/java/play/core/PathsTest.java index 4a33fb9b116..97cf22e76d1 100644 --- a/core/play/src/test/java/play/core/PathsTest.java +++ b/core/play/src/test/java/play/core/PathsTest.java @@ -8,10 +8,10 @@ import org.junit.jupiter.api.Test; -public class PathsTest { +class PathsTest { @Test - public void relativePathShouldReturnSiblingPathWithoutCommonRoot() { + void relativePathShouldReturnSiblingPathWithoutCommonRoot() { final String startPath = "/playframework"; final String targetPath = "/one"; @@ -19,7 +19,7 @@ public void relativePathShouldReturnSiblingPathWithoutCommonRoot() { } @Test - public void relativeShouldReturnSiblingPathWithoutCommonRoot() { + void relativeShouldReturnSiblingPathWithoutCommonRoot() { final String startPath = "/one/two"; final String targetPath = "/one/two/asset.js"; @@ -27,7 +27,7 @@ public void relativeShouldReturnSiblingPathWithoutCommonRoot() { } @Test - public void relativeIncludeOneParentDirAndLastCommonElementOfTargetRouteWithNoTrailingSlash() { + void relativeIncludeOneParentDirAndLastCommonElementOfTargetRouteWithNoTrailingSlash() { final String startPath = "/one/two"; final String targetPath = "/one"; @@ -35,7 +35,7 @@ public void relativeIncludeOneParentDirAndLastCommonElementOfTargetRouteWithNoTr } @Test - public void relativePathShouldIncludeOneParentDirectoryAndNoLastCommonElement() { + void relativePathShouldIncludeOneParentDirectoryAndNoLastCommonElement() { final String startPath = "/one/two/"; final String targetPath = "/one/"; @@ -43,7 +43,7 @@ public void relativePathShouldIncludeOneParentDirectoryAndNoLastCommonElement() } @Test - public void relativePathShouldIncludeTwoParentDirectory() { + void relativePathShouldIncludeTwoParentDirectory() { final String startPath = "/one/two"; final String targetPath = "/one-b/two-b"; @@ -51,7 +51,7 @@ public void relativePathShouldIncludeTwoParentDirectory() { } @Test - public void relativePathShouldNoCommonRootSegmentsAndIncludeThreeParentDirectories() { + void relativePathShouldNoCommonRootSegmentsAndIncludeThreeParentDirectories() { final String startPath = "/one/two/three"; final String targetPath = "/one-b/two-b/asset.js"; @@ -59,7 +59,7 @@ public void relativePathShouldNoCommonRootSegmentsAndIncludeThreeParentDirectori } @Test - public void relativePathShouldHaveTwoCommonRootSegmentsAndIncludeTwoParentDirectories() { + void relativePathShouldHaveTwoCommonRootSegmentsAndIncludeTwoParentDirectories() { final String startPath = "/one/two/three/four"; final String targetPath = "/one/two/three-b/four-b/asset.js"; @@ -67,7 +67,7 @@ public void relativePathShouldHaveTwoCommonRootSegmentsAndIncludeTwoParentDirect } @Test - public void relativePathShouldRetainTrailingForwardSlashIfItExistsInCall() { + void relativePathShouldRetainTrailingForwardSlashIfItExistsInCall() { final String startPath = "/one/two"; final String targetPath = "/one/two-c/"; @@ -75,7 +75,7 @@ public void relativePathShouldRetainTrailingForwardSlashIfItExistsInCall() { } @Test - public void relativePathReturnCurrentDir() { + void relativePathReturnCurrentDir() { final String startPath = "/one/two"; final String targetPath = "/one/two"; @@ -83,7 +83,7 @@ public void relativePathReturnCurrentDir() { } @Test - public void relativePathReturnCurrentDirIncludeFourParentDirectories() { + void relativePathReturnCurrentDirIncludeFourParentDirectories() { final String startPath = "/one/two//three/../three-b/./four/"; final String targetPath = "/one-b//two-b/./"; @@ -91,21 +91,21 @@ public void relativePathReturnCurrentDirIncludeFourParentDirectories() { } @Test - public void canonicalPathReturnHandlesParentDirectories() { + void canonicalPathReturnHandlesParentDirectories() { final String targetPath = "/one/two/../two-b/three"; assertEquals("/one/two-b/three", Paths.canonical(targetPath)); } @Test - public void canonicalPathHandlesCurrentDirectories() { + void canonicalPathHandlesCurrentDirectories() { final String targetPath = "/one/two/./three"; assertEquals("/one/two/three", Paths.canonical(targetPath)); } @Test - public void canonicalPathHandlesMultipleDirectorySeparators() { + void canonicalPathHandlesMultipleDirectorySeparators() { final String targetPath = "/one/two//three"; assertEquals("/one/two/three", Paths.canonical(targetPath)); diff --git a/core/play/src/test/java/play/i18n/MessagesTest.java b/core/play/src/test/java/play/i18n/MessagesTest.java index 4c1baf9de36..810b6404f92 100644 --- a/core/play/src/test/java/play/i18n/MessagesTest.java +++ b/core/play/src/test/java/play/i18n/MessagesTest.java @@ -9,10 +9,10 @@ import org.junit.jupiter.api.Test; -public class MessagesTest { +class MessagesTest { @Test - public void testMessageCall() { + void testMessageCall() { MessagesApi messagesApi = mock(MessagesApi.class); Lang lang = Lang.forCode("en-US"); MessagesImpl messages = new MessagesImpl(lang, messagesApi); diff --git a/core/play/src/test/java/play/libs/concurrent/FuturesTest.java b/core/play/src/test/java/play/libs/concurrent/FuturesTest.java index 83cd985aab1..92af59dd057 100644 --- a/core/play/src/test/java/play/libs/concurrent/FuturesTest.java +++ b/core/play/src/test/java/play/libs/concurrent/FuturesTest.java @@ -17,25 +17,25 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -public class FuturesTest { +class FuturesTest { private ActorSystem system; private Futures futures; @BeforeEach - public void setup() { + void setup() { system = ActorSystem.create(); futures = new DefaultFutures(new play.api.libs.concurrent.DefaultFutures(system)); } @AfterEach - public void teardown() { + void teardown() { system.terminate(); futures = null; } @Test - public void successfulTimeout() throws Exception { + void successfulTimeout() throws Exception { class MyClass { CompletionStage callWithTimeout() { return futures.timeout(computePIAsynchronously(), Duration.ofSeconds(1)); @@ -48,7 +48,7 @@ CompletionStage callWithTimeout() { } @Test - public void failedTimeout() throws Exception { + void failedTimeout() throws Exception { class MyClass { CompletionStage callWithTimeout() { return futures.timeout(delayByOneSecond(), Duration.ofMillis(300)); @@ -65,7 +65,7 @@ CompletionStage callWithTimeout() { } @Test - public void successfulDelayed() throws Exception { + void successfulDelayed() throws Exception { Duration expected = Duration.ofSeconds(3); final CompletionStage stage = renderAfter(expected); @@ -76,7 +76,7 @@ public void successfulDelayed() throws Exception { } @Test - public void failedDelayed() throws Exception { + void failedDelayed() throws Exception { Duration expected = Duration.ofSeconds(3); final CompletionStage stage = renderAfter(Duration.ofSeconds(1)); @@ -87,7 +87,7 @@ public void failedDelayed() throws Exception { } @Test - public void testDelay() throws Exception { + void testDelay() throws Exception { Duration expected = Duration.ofSeconds(2); long start = System.currentTimeMillis(); CompletionStage stage = diff --git a/core/play/src/test/java/play/mvc/CallTest.java b/core/play/src/test/java/play/mvc/CallTest.java index 1857bacbf9d..2135a8bbe15 100644 --- a/core/play/src/test/java/play/mvc/CallTest.java +++ b/core/play/src/test/java/play/mvc/CallTest.java @@ -10,24 +10,24 @@ import play.mvc.Http.Request; import play.mvc.Http.RequestBuilder; -public class CallTest { +class CallTest { @Test - public void calShouldReturnCorrectUrlInPath() { + void calShouldReturnCorrectUrlInPath() { final TestCall call = new TestCall("/myurl", "GET"); assertEquals("/myurl", call.path()); } @Test - public void callShouldReturnCorrectUrlAndFragmentInPath() { + void callShouldReturnCorrectUrlAndFragmentInPath() { final Call call = new TestCall("/myurl", "GET").withFragment("myfragment"); assertEquals("/myurl#myfragment", call.path()); } @Test - public void absoluteURLWithRequestShouldHaveHTTPScheme() { + void absoluteURLWithRequestShouldHaveHTTPScheme() { final Request req = new RequestBuilder().uri("http://playframework.com/playframework").build(); final TestCall call = new TestCall("/url", "GET"); @@ -36,7 +36,7 @@ public void absoluteURLWithRequestShouldHaveHTTPScheme() { } @Test - public void absoluteURLWithRequestAndSecureParameterIsFalseShouldHaveHTTPScheme() { + void absoluteURLWithRequestAndSecureParameterIsFalseShouldHaveHTTPScheme() { final Request req = new RequestBuilder().uri("https://playframework.com/playframework").build(); final TestCall call = new TestCall("/url", "GET"); @@ -45,14 +45,14 @@ public void absoluteURLWithRequestAndSecureParameterIsFalseShouldHaveHTTPScheme( } @Test - public void absoluteURLWithHostAndSecureParameterIsFalseShouldHaveHTTPScheme() { + void absoluteURLWithHostAndSecureParameterIsFalseShouldHaveHTTPScheme() { final TestCall call = new TestCall("/url", "GET"); assertEquals("http://typesafe.com/url", call.absoluteURL(false, "typesafe.com")); } @Test - public void absoluteURLWithRequestShouldHaveHTTPSScheme() { + void absoluteURLWithRequestShouldHaveHTTPSScheme() { final Request req = new RequestBuilder().uri("https://playframework.com/playframework").build(); final TestCall call = new TestCall("/url", "GET"); @@ -61,7 +61,7 @@ public void absoluteURLWithRequestShouldHaveHTTPSScheme() { } @Test - public void absoluteUrlWithRequestAndSecureParameterIsTrueShouldHaveHTTPSScheme() { + void absoluteUrlWithRequestAndSecureParameterIsTrueShouldHaveHTTPSScheme() { final Request req = new RequestBuilder().uri("http://playframework.com/playframework").build(); final TestCall call = new TestCall("/url", "GET"); @@ -70,14 +70,14 @@ public void absoluteUrlWithRequestAndSecureParameterIsTrueShouldHaveHTTPSScheme( } @Test - public void absoluteURLWithHostAndSecureParameterIsTrueShouldHaveHTTPSScheme() { + void absoluteURLWithHostAndSecureParameterIsTrueShouldHaveHTTPSScheme() { final TestCall call = new TestCall("/url", "GET"); assertEquals("https://typesafe.com/url", call.absoluteURL(true, "typesafe.com")); } @Test - public void webSocketURLWithRequestShouldHaveHTTPScheme() { + void webSocketURLWithRequestShouldHaveHTTPScheme() { final Request req = new RequestBuilder().uri("http://playframework.com/playframework").build(); final TestCall call = new TestCall("/url", "GET"); @@ -86,7 +86,7 @@ public void webSocketURLWithRequestShouldHaveHTTPScheme() { } @Test - public void webSocketURLWithRequestAndSecureParameterIsFalseShouldHaveHTTPScheme() { + void webSocketURLWithRequestAndSecureParameterIsFalseShouldHaveHTTPScheme() { final Request req = new RequestBuilder().uri("https://playframework.com/playframework").build(); final TestCall call = new TestCall("/url", "GET"); @@ -95,14 +95,14 @@ public void webSocketURLWithRequestAndSecureParameterIsFalseShouldHaveHTTPScheme } @Test - public void webSocketURLWithHostAndSecureParameterIsFalseShouldHaveHTTPScheme() { + void webSocketURLWithHostAndSecureParameterIsFalseShouldHaveHTTPScheme() { final TestCall call = new TestCall("/url", "GET"); assertEquals("ws://typesafe.com/url", call.webSocketURL(false, "typesafe.com")); } @Test - public void webSocketURLWithRequestShouldHaveHTTPSScheme() { + void webSocketURLWithRequestShouldHaveHTTPSScheme() { final Request req = new RequestBuilder().uri("https://playframework.com/playframework").build(); final TestCall call = new TestCall("/url", "GET"); @@ -111,7 +111,7 @@ public void webSocketURLWithRequestShouldHaveHTTPSScheme() { } @Test - public void webSocketURLWithRequestAndSecureParameterIsTrueShouldHaveHTTPSScheme() { + void webSocketURLWithRequestAndSecureParameterIsTrueShouldHaveHTTPSScheme() { final Request req = new RequestBuilder().uri("http://playframework.com/playframework").build(); final TestCall call = new TestCall("/url", "GET"); @@ -120,14 +120,14 @@ public void webSocketURLWithRequestAndSecureParameterIsTrueShouldHaveHTTPSScheme } @Test - public void webSocketURLWithHostAndSecureParameterIsTrueShouldHaveHTTPSScheme() { + void webSocketURLWithHostAndSecureParameterIsTrueShouldHaveHTTPSScheme() { final TestCall call = new TestCall("/url", "GET"); assertEquals("wss://typesafe.com/url", call.webSocketURL(true, "typesafe.com")); } @Test - public void relativePathTakesStartPathFromRequest() { + void relativePathTakesStartPathFromRequest() { final Request req = new RequestBuilder().uri("http://playframework.com/one/two").build(); final TestCall call = new TestCall("/one/two-b", "GET"); @@ -136,7 +136,7 @@ public void relativePathTakesStartPathFromRequest() { } @Test - public void relativePathTakesStartPathAsString() { + void relativePathTakesStartPathAsString() { final String startPath = "/one/two"; final TestCall call = new TestCall("/one/two-b", "GET"); @@ -145,7 +145,7 @@ public void relativePathTakesStartPathAsString() { } @Test - public void relativePathIncludesFragment() { + void relativePathIncludesFragment() { final Request req = new RequestBuilder().uri("http://playframework.com/one/two").build(); final TestCall call = new TestCall("/one/two-b", "GET", "foo"); @@ -154,7 +154,7 @@ public void relativePathIncludesFragment() { } @Test - public void canonicalPathReturnedFromCall() { + void canonicalPathReturnedFromCall() { final TestCall call = new TestCall("/one/.././two//three-b", "GET"); assertEquals("/two/three-b", call.canonical()); diff --git a/core/play/src/test/java/play/mvc/CookieBuilderTest.java b/core/play/src/test/java/play/mvc/CookieBuilderTest.java index 4c9b734a0c2..46fff968575 100644 --- a/core/play/src/test/java/play/mvc/CookieBuilderTest.java +++ b/core/play/src/test/java/play/mvc/CookieBuilderTest.java @@ -8,10 +8,10 @@ import org.junit.jupiter.api.Test; -public class CookieBuilderTest { +class CookieBuilderTest { @Test - public void createACookieWithNameAndValueAndKeepDefaults() { + void createACookieWithNameAndValueAndKeepDefaults() { Http.Cookie cookie = Http.Cookie.builder("name", "value").build(); assertEquals("name", cookie.name()); assertEquals("value", cookie.value()); @@ -23,7 +23,7 @@ public void createACookieWithNameAndValueAndKeepDefaults() { } @Test - public void createACookieWithNameAndValueAndChangePath() { + void createACookieWithNameAndValueAndChangePath() { Http.Cookie cookie = Http.Cookie.builder("name", "value").withPath("path1/path").build(); assertEquals("name", cookie.name()); assertEquals("value", cookie.value()); @@ -35,7 +35,7 @@ public void createACookieWithNameAndValueAndChangePath() { } @Test - public void createACookieWithNameAndValueAndChangeDomain() { + void createACookieWithNameAndValueAndChangeDomain() { Http.Cookie cookie = Http.Cookie.builder("name", "value").withDomain(".example.com").build(); assertEquals("name", cookie.name()); assertEquals("value", cookie.value()); @@ -47,7 +47,7 @@ public void createACookieWithNameAndValueAndChangeDomain() { } @Test - public void createACookieWithNameAndValueWithSecureAndHttpOnlyEqualToTrue() { + void createACookieWithNameAndValueWithSecureAndHttpOnlyEqualToTrue() { Http.Cookie cookie = Http.Cookie.builder("name", "value").withSecure(true).withHttpOnly(true).build(); assertEquals("name", cookie.name()); diff --git a/core/play/src/test/java/play/mvc/RangeResultsTest.java b/core/play/src/test/java/play/mvc/RangeResultsTest.java index 428b14a5c2b..8fced7bada4 100644 --- a/core/play/src/test/java/play/mvc/RangeResultsTest.java +++ b/core/play/src/test/java/play/mvc/RangeResultsTest.java @@ -32,26 +32,26 @@ import scala.concurrent.duration.Duration; import scala.jdk.javaapi.FutureConverters; -public class RangeResultsTest { +class RangeResultsTest { private static Path path; @BeforeAll - public static void createFile() throws IOException { + static void createFile() throws IOException { path = Paths.get("test.tmp"); Files.createFile(path); Files.write(path, "Some content for the file".getBytes(), StandardOpenOption.APPEND); } @AfterAll - public static void deleteFile() throws IOException { + static void deleteFile() throws IOException { Files.deleteIfExists(path); } // -- InputStreams @Test - public void shouldNotReturnRangeResultForInputStreamWhenHeaderIsNotPresent() throws IOException { + void shouldNotReturnRangeResultForInputStreamWhenHeaderIsNotPresent() throws IOException { Http.Request req = mockRegularRequest(); try (InputStream stream = Files.newInputStream(path)) { Result result = RangeResults.ofStream(req, stream); @@ -61,7 +61,7 @@ public void shouldNotReturnRangeResultForInputStreamWhenHeaderIsNotPresent() thr } @Test - public void shouldReturnRangeResultForInputStreamWhenHeaderIsPresentAndContentTypeWasSpecified() + void shouldReturnRangeResultForInputStreamWhenHeaderIsPresentAndContentTypeWasSpecified() throws IOException { Http.Request req = mockRangeRequest(); try (InputStream stream = Files.newInputStream(path)) { @@ -72,7 +72,7 @@ public void shouldReturnRangeResultForInputStreamWhenHeaderIsPresentAndContentTy } @Test - public void shouldReturnRangeResultForInputStreamWithCustomFilename() throws IOException { + void shouldReturnRangeResultForInputStreamWithCustomFilename() throws IOException { Http.Request req = mockRangeRequest(); try (InputStream stream = Files.newInputStream(path)) { Result result = RangeResults.ofStream(req, stream, Files.size(path), "file.txt"); @@ -83,7 +83,7 @@ public void shouldReturnRangeResultForInputStreamWithCustomFilename() throws IOE } @Test - public void shouldNotReturnRangeResultForInputStreamWhenHeaderIsNotPresentWithCustomFilename() + void shouldNotReturnRangeResultForInputStreamWhenHeaderIsNotPresentWithCustomFilename() throws IOException { Http.Request req = mockRegularRequest(); try (InputStream stream = Files.newInputStream(path)) { @@ -96,7 +96,7 @@ public void shouldNotReturnRangeResultForInputStreamWhenHeaderIsNotPresentWithCu } @Test - public void shouldReturnPartialContentForInputStreamWithGivenEntityLength() throws IOException { + void shouldReturnPartialContentForInputStreamWithGivenEntityLength() throws IOException { Http.Request req = mockRangeRequest(); try (InputStream stream = Files.newInputStream(path)) { Result result = RangeResults.ofStream(req, stream, Files.size(path)); @@ -106,8 +106,7 @@ public void shouldReturnPartialContentForInputStreamWithGivenEntityLength() thro } @Test - public void shouldReturnPartialContentForInputStreamWithGivenNameAndContentType() - throws IOException { + void shouldReturnPartialContentForInputStreamWithGivenNameAndContentType() throws IOException { Http.Request req = mockRangeRequest(); try (InputStream stream = Files.newInputStream(path)) { Result result = RangeResults.ofStream(req, stream, Files.size(path), "file.txt", TEXT); @@ -121,7 +120,7 @@ public void shouldReturnPartialContentForInputStreamWithGivenNameAndContentType( // -- Paths @Test - public void shouldReturnRangeResultForPath() { + void shouldReturnRangeResultForPath() { Http.Request req = mockRangeRequest(); Result result = RangeResults.ofPath(req, path); @@ -131,7 +130,7 @@ public void shouldReturnRangeResultForPath() { } @Test - public void shouldNotReturnRangeResultForPathWhenHeaderIsNotPresent() { + void shouldNotReturnRangeResultForPathWhenHeaderIsNotPresent() { Http.Request req = mockRegularRequest(); Result result = RangeResults.ofPath(req, path); @@ -142,7 +141,7 @@ public void shouldNotReturnRangeResultForPathWhenHeaderIsNotPresent() { } @Test - public void shouldReturnRangeResultForPathWithCustomFilename() { + void shouldReturnRangeResultForPathWithCustomFilename() { Http.Request req = mockRangeRequest(); Result result = RangeResults.ofPath(req, path, "file.txt"); @@ -152,7 +151,7 @@ public void shouldReturnRangeResultForPathWithCustomFilename() { } @Test - public void shouldNotReturnRangeResultForPathWhenHeaderIsNotPresentWithCustomFilename() { + void shouldNotReturnRangeResultForPathWhenHeaderIsNotPresentWithCustomFilename() { Http.Request req = mockRegularRequest(); Result result = RangeResults.ofPath(req, path, "file.txt"); @@ -163,7 +162,7 @@ public void shouldNotReturnRangeResultForPathWhenHeaderIsNotPresentWithCustomFil } @Test - public void shouldReturnRangeResultForPathWhenFilenameHasSpecialChars() { + void shouldReturnRangeResultForPathWhenFilenameHasSpecialChars() { Http.Request req = mockRangeRequest(); Result result = RangeResults.ofPath(req, path, "测 试.tmp"); @@ -175,7 +174,7 @@ public void shouldReturnRangeResultForPathWhenFilenameHasSpecialChars() { } @Test - public void shouldNotReturnRangeResultForPathWhenFilenameHasSpecialChars() { + void shouldNotReturnRangeResultForPathWhenFilenameHasSpecialChars() { Http.Request req = mockRegularRequest(); Result result = RangeResults.ofPath(req, path, "测 试.tmp"); @@ -189,7 +188,7 @@ public void shouldNotReturnRangeResultForPathWhenFilenameHasSpecialChars() { // -- Files @Test - public void shouldReturnRangeResultForFile() { + void shouldReturnRangeResultForFile() { Http.Request req = mockRangeRequest(); Result result = RangeResults.ofFile(req, path.toFile()); @@ -199,7 +198,7 @@ public void shouldReturnRangeResultForFile() { } @Test - public void shouldNotReturnRangeResultForFileWhenHeaderIsNotPresent() { + void shouldNotReturnRangeResultForFileWhenHeaderIsNotPresent() { Http.Request req = mockRegularRequest(); Result result = RangeResults.ofFile(req, path.toFile()); @@ -210,7 +209,7 @@ public void shouldNotReturnRangeResultForFileWhenHeaderIsNotPresent() { } @Test - public void shouldReturnRangeResultForFileWithCustomFilename() { + void shouldReturnRangeResultForFileWithCustomFilename() { Http.Request req = mockRangeRequest(); Result result = RangeResults.ofFile(req, path.toFile(), "file.txt"); @@ -220,7 +219,7 @@ public void shouldReturnRangeResultForFileWithCustomFilename() { } @Test - public void shouldNotReturnRangeResultForFileWhenHeaderIsNotPresentWithCustomFilename() { + void shouldNotReturnRangeResultForFileWhenHeaderIsNotPresentWithCustomFilename() { Http.Request req = mockRegularRequest(); Result result = RangeResults.ofFile(req, path.toFile(), "file.txt"); @@ -231,7 +230,7 @@ public void shouldNotReturnRangeResultForFileWhenHeaderIsNotPresentWithCustomFil } @Test - public void shouldReturnRangeResultForFileWhenFilenameHasSpecialChars() { + void shouldReturnRangeResultForFileWhenFilenameHasSpecialChars() { Http.Request req = mockRangeRequest(); Result result = RangeResults.ofFile(req, path.toFile(), "测 试.tmp"); @@ -243,7 +242,7 @@ public void shouldReturnRangeResultForFileWhenFilenameHasSpecialChars() { } @Test - public void shouldNotReturnRangeResultForFileWhenFilenameHasSpecialChars() { + void shouldNotReturnRangeResultForFileWhenFilenameHasSpecialChars() { Http.Request req = mockRegularRequest(); Result result = RangeResults.ofFile(req, path.toFile(), "测 试.tmp"); @@ -257,7 +256,7 @@ public void shouldNotReturnRangeResultForFileWhenFilenameHasSpecialChars() { // -- Sources @Test - public void shouldNotReturnRangeResultForSourceWhenHeaderIsNotPresent() throws IOException { + void shouldNotReturnRangeResultForSourceWhenHeaderIsNotPresent() throws IOException { Http.Request req = mockRegularRequest(); Source> source = FileIO.fromPath(path); @@ -269,7 +268,7 @@ public void shouldNotReturnRangeResultForSourceWhenHeaderIsNotPresent() throws I } @Test - public void shouldReturnRangeResultForSourceWhenHeaderIsPresentAndContentTypeWasSpecified() + void shouldReturnRangeResultForSourceWhenHeaderIsPresentAndContentTypeWasSpecified() throws IOException { Http.Request req = mockRangeRequest(); @@ -282,7 +281,7 @@ public void shouldReturnRangeResultForSourceWhenHeaderIsPresentAndContentTypeWas } @Test - public void shouldReturnRangeResultForSourceWithCustomFilename() throws IOException { + void shouldReturnRangeResultForSourceWithCustomFilename() throws IOException { Http.Request req = mockRangeRequest(); Source> source = FileIO.fromPath(path); @@ -295,7 +294,7 @@ public void shouldReturnRangeResultForSourceWithCustomFilename() throws IOExcept } @Test - public void shouldNotReturnRangeResultForSourceWhenHeaderIsNotPresentWithCustomFilename() + void shouldNotReturnRangeResultForSourceWhenHeaderIsNotPresentWithCustomFilename() throws IOException { Http.Request req = mockRegularRequest(); @@ -309,7 +308,7 @@ public void shouldNotReturnRangeResultForSourceWhenHeaderIsNotPresentWithCustomF } @Test - public void shouldReturnPartialContentForSourceWithGivenEntityLength() throws IOException { + void shouldReturnPartialContentForSourceWithGivenEntityLength() throws IOException { Http.Request req = mockRangeRequest(); long entityLength = Files.size(path); @@ -323,7 +322,7 @@ public void shouldReturnPartialContentForSourceWithGivenEntityLength() throws IO } @Test - public void shouldNotReturnRangeResultForStreamWhenFilenameHasSpecialChars() throws IOException { + void shouldNotReturnRangeResultForStreamWhenFilenameHasSpecialChars() throws IOException { Http.Request req = mockRegularRequest(); Source> source = FileIO.fromPath(path); @@ -337,7 +336,7 @@ public void shouldNotReturnRangeResultForStreamWhenFilenameHasSpecialChars() thr } @Test - public void shouldReturnRangeResultForStreamWhenFilenameHasSpecialChars() throws IOException { + void shouldReturnRangeResultForStreamWhenFilenameHasSpecialChars() throws IOException { Http.Request req = mockRangeRequest(); long entityLength = Files.size(path); @@ -352,7 +351,7 @@ public void shouldReturnRangeResultForStreamWhenFilenameHasSpecialChars() throws } @Test - public void shouldHandlePreSeekingSource() throws Exception { + void shouldHandlePreSeekingSource() throws Exception { Http.Request req = mockRangeRequestWithOffset(); long entityLength = Files.size(path); byte[] data = "abcdefghijklmnopqrstuvwxyz".getBytes(); @@ -362,7 +361,7 @@ public void shouldHandlePreSeekingSource() throws Exception { } @Test - public void shouldHandleNoSeekingSource() throws Exception { + void shouldHandleNoSeekingSource() throws Exception { Http.Request req = mockRangeRequestWithOffset(); long entityLength = Files.size(path); byte[] data = "abcdefghijklmnopqrstuvwxyz".getBytes(); @@ -372,7 +371,7 @@ public void shouldHandleNoSeekingSource() throws Exception { } @Test - public void shouldRejectBrokenSourceFunction() throws Exception { + void shouldRejectBrokenSourceFunction() throws Exception { Http.Request req = mockRangeRequestWithOffset(); long entityLength = Files.size(path); byte[] data = "abcdefghijklmnopqrstuvwxyz".getBytes(); diff --git a/core/play/src/test/java/play/mvc/ResultsTest.java b/core/play/src/test/java/play/mvc/ResultsTest.java index 0308d34853a..3b3f5f17622 100644 --- a/core/play/src/test/java/play/mvc/ResultsTest.java +++ b/core/play/src/test/java/play/mvc/ResultsTest.java @@ -27,26 +27,26 @@ import scala.concurrent.duration.Duration; import scala.jdk.javaapi.FutureConverters; -public class ResultsTest { +class ResultsTest { private static Path file; private static final boolean INLINE_FILE = true; private static final boolean ATTACHMENT_FILE = false; @BeforeAll - public static void createFile() throws Exception { + static void createFile() throws Exception { file = Paths.get("test.tmp"); Files.createFile(file); Files.write(file, "Some content for the file".getBytes(), StandardOpenOption.APPEND); } @AfterAll - public static void deleteFile() throws IOException { + static void deleteFile() throws IOException { Files.deleteIfExists(file); } @Test - public void shouldCopyFlashWhenCallingResultAs() { + void shouldCopyFlashWhenCallingResultAs() { Map flash = new HashMap<>(); flash.put("flash.message", "flash message value"); Result result = Results.redirect("/somewhere").withFlash(flash); @@ -58,7 +58,7 @@ public void shouldCopyFlashWhenCallingResultAs() { } @Test - public void shouldCopySessionWhenCallingResultAs() { + void shouldCopySessionWhenCallingResultAs() { Map session = new HashMap<>(); session.put("session.message", "session message value"); Result result = Results.ok("Result test body").withSession(session); @@ -70,14 +70,14 @@ public void shouldCopySessionWhenCallingResultAs() { } @Test - public void shouldCopyHeadersWhenCallingResultAs() { + void shouldCopyHeadersWhenCallingResultAs() { Result result = Results.ok("Result test body").withHeader("X-Header", "header value"); Result as = result.as(Http.MimeTypes.HTML); assertEquals("header value", as.header("X-Header").get()); } @Test - public void shouldCopyCookiesWhenCallingResultAs() { + void shouldCopyCookiesWhenCallingResultAs() { Result result = Results.ok("Result test body") .withCookies(Http.Cookie.builder("cookie-name", "cookie value").build()) @@ -89,12 +89,12 @@ public void shouldCopyCookiesWhenCallingResultAs() { // -- Path tests @Test() - public void shouldThrowNullPointerExceptionIfPathIsNull() { + void shouldThrowNullPointerExceptionIfPathIsNull() { assertThrowsExactly(NullPointerException.class, () -> Results.ok().sendPath(null)); } @Test - public void sendPathWithOKStatus() { + void sendPathWithOKStatus() { Result result = Results.ok().sendPath(file); assertEquals(Http.Status.OK, result.status()); assertEquals( @@ -102,7 +102,7 @@ public void sendPathWithOKStatus() { } @Test - public void sendPathWithUnauthorizedStatus() { + void sendPathWithUnauthorizedStatus() { Result result = Results.unauthorized().sendPath(file); assertEquals(Http.Status.UNAUTHORIZED, result.status()); assertEquals( @@ -110,7 +110,7 @@ public void sendPathWithUnauthorizedStatus() { } @Test - public void sendPathAsAttachmentWithUnauthorizedStatus() { + void sendPathAsAttachmentWithUnauthorizedStatus() { Result result = Results.unauthorized().sendPath(file, ATTACHMENT_FILE); assertEquals(Http.Status.UNAUTHORIZED, result.status()); assertEquals( @@ -118,7 +118,7 @@ public void sendPathAsAttachmentWithUnauthorizedStatus() { } @Test - public void sendPathAsAttachmentWithOkStatus() { + void sendPathAsAttachmentWithOkStatus() { Result result = Results.ok().sendPath(file, ATTACHMENT_FILE); assertEquals(Http.Status.OK, result.status()); assertEquals( @@ -126,7 +126,7 @@ public void sendPathAsAttachmentWithOkStatus() { } @Test - public void sendPathWithFileName() { + void sendPathWithFileName() { Result result = Results.unauthorized().sendPath(file, Optional.of("foo.bar")); assertEquals(Http.Status.UNAUTHORIZED, result.status()); assertEquals( @@ -134,7 +134,7 @@ public void sendPathWithFileName() { } @Test - public void sendPathInlineWithFileName() { + void sendPathInlineWithFileName() { Result result = Results.unauthorized().sendPath(file, INLINE_FILE, Optional.of("foo.bar")); assertEquals(Http.Status.UNAUTHORIZED, result.status()); assertEquals( @@ -142,21 +142,21 @@ public void sendPathInlineWithFileName() { } @Test - public void sendPathInlineWithoutFileName() { + void sendPathInlineWithoutFileName() { Result result = Results.unauthorized().sendPath(file, Optional.empty()); assertEquals(Http.Status.UNAUTHORIZED, result.status()); assertEquals(Optional.empty(), result.header(HeaderNames.CONTENT_DISPOSITION)); } @Test - public void sendPathAsAttachmentWithoutFileName() { + void sendPathAsAttachmentWithoutFileName() { Result result = Results.unauthorized().sendPath(file, ATTACHMENT_FILE, Optional.empty()); assertEquals(Http.Status.UNAUTHORIZED, result.status()); assertEquals("attachment", result.header(HeaderNames.CONTENT_DISPOSITION).get()); } @Test - public void sendPathWithFileNameHasSpecialChars() { + void sendPathWithFileNameHasSpecialChars() { Result result = Results.ok().sendPath(file, INLINE_FILE, Optional.of("测 试.tmp")); assertEquals(Http.Status.OK, result.status()); assertEquals( @@ -167,12 +167,12 @@ public void sendPathWithFileNameHasSpecialChars() { // -- File tests @Test - public void shouldThrowNullPointerExceptionIfFileIsNull() { + void shouldThrowNullPointerExceptionIfFileIsNull() { Assertions.assertThrowsExactly(NullPointerException.class, () -> Results.ok().sendFile(null)); } @Test - public void sendFileWithOKStatus() { + void sendFileWithOKStatus() { Result result = Results.ok().sendFile(file.toFile()); assertEquals(Http.Status.OK, result.status()); assertEquals( @@ -180,7 +180,7 @@ public void sendFileWithOKStatus() { } @Test - public void sendFileWithUnauthorizedStatus() { + void sendFileWithUnauthorizedStatus() { Result result = Results.unauthorized().sendFile(file.toFile()); assertEquals(Http.Status.UNAUTHORIZED, result.status()); assertEquals( @@ -188,7 +188,7 @@ public void sendFileWithUnauthorizedStatus() { } @Test - public void sendFileAsAttachmentWithUnauthorizedStatus() { + void sendFileAsAttachmentWithUnauthorizedStatus() { Result result = Results.unauthorized().sendFile(file.toFile(), ATTACHMENT_FILE); assertEquals(Http.Status.UNAUTHORIZED, result.status()); assertEquals( @@ -196,7 +196,7 @@ public void sendFileAsAttachmentWithUnauthorizedStatus() { } @Test - public void sendFileAsAttachmentWithOkStatus() { + void sendFileAsAttachmentWithOkStatus() { Result result = Results.ok().sendFile(file.toFile(), ATTACHMENT_FILE); assertEquals(Http.Status.OK, result.status()); assertEquals( @@ -204,7 +204,7 @@ public void sendFileAsAttachmentWithOkStatus() { } @Test - public void sendFileWithFileName() { + void sendFileWithFileName() { Result result = Results.unauthorized().sendFile(file.toFile(), Optional.of("foo.bar")); assertEquals(Http.Status.UNAUTHORIZED, result.status()); assertEquals( @@ -212,7 +212,7 @@ public void sendFileWithFileName() { } @Test - public void sendFileInlineWithFileName() { + void sendFileInlineWithFileName() { Result result = Results.ok().sendFile(file.toFile(), INLINE_FILE, Optional.of("foo.bar")); assertEquals(Http.Status.OK, result.status()); assertEquals( @@ -220,21 +220,21 @@ public void sendFileInlineWithFileName() { } @Test - public void sendFileInlineWithoutFileName() { + void sendFileInlineWithoutFileName() { Result result = Results.ok().sendFile(file.toFile(), Optional.empty()); assertEquals(Http.Status.OK, result.status()); assertEquals(Optional.empty(), result.header(HeaderNames.CONTENT_DISPOSITION)); } @Test - public void sendFileAsAttachmentWithoutFileName() { + void sendFileAsAttachmentWithoutFileName() { Result result = Results.ok().sendFile(file.toFile(), ATTACHMENT_FILE, Optional.empty()); assertEquals(Http.Status.OK, result.status()); assertEquals("attachment", result.header(HeaderNames.CONTENT_DISPOSITION).get()); } @Test - public void sendFileWithFileNameHasSpecialChars() { + void sendFileWithFileNameHasSpecialChars() { Result result = Results.ok().sendFile(file.toFile(), INLINE_FILE, Optional.of("测 试.tmp")); assertEquals(Http.Status.OK, result.status()); assertEquals( @@ -243,7 +243,7 @@ public void sendFileWithFileNameHasSpecialChars() { } @Test - public void sendFileHonoringOnClose() throws TimeoutException, InterruptedException { + void sendFileHonoringOnClose() throws TimeoutException, InterruptedException { ActorSystem actorSystem = ActorSystem.create("TestSystem"); Materializer mat = Materializer.matFromSystem(actorSystem); try { @@ -265,7 +265,7 @@ public void sendFileHonoringOnClose() throws TimeoutException, InterruptedExcept } @Test - public void sendPathHonoringOnClose() throws TimeoutException, InterruptedException { + void sendPathHonoringOnClose() throws TimeoutException, InterruptedException { ActorSystem actorSystem = ActorSystem.create("TestSystem"); Materializer mat = Materializer.matFromSystem(actorSystem); try { @@ -287,7 +287,7 @@ public void sendPathHonoringOnClose() throws TimeoutException, InterruptedExcept } @Test - public void sendResourceHonoringOnClose() throws TimeoutException, InterruptedException { + void sendResourceHonoringOnClose() throws TimeoutException, InterruptedException { ActorSystem actorSystem = ActorSystem.create("TestSystem"); Materializer mat = Materializer.matFromSystem(actorSystem); try { @@ -310,7 +310,7 @@ public void sendResourceHonoringOnClose() throws TimeoutException, InterruptedEx } @Test - public void sendInputStreamHonoringOnClose() throws TimeoutException, InterruptedException { + void sendInputStreamHonoringOnClose() throws TimeoutException, InterruptedException { ActorSystem actorSystem = ActorSystem.create("TestSystem"); Materializer mat = Materializer.matFromSystem(actorSystem); try { @@ -338,8 +338,7 @@ public void sendInputStreamHonoringOnClose() throws TimeoutException, Interrupte } @Test - public void sendInputStreamChunkedHonoringOnClose() - throws TimeoutException, InterruptedException { + void sendInputStreamChunkedHonoringOnClose() throws TimeoutException, InterruptedException { ActorSystem actorSystem = ActorSystem.create("TestSystem"); Materializer mat = Materializer.matFromSystem(actorSystem); try { @@ -364,7 +363,7 @@ public void sendInputStreamChunkedHonoringOnClose() } @Test - public void getOptionalCookie() { + void getOptionalCookie() { Result result = Results.ok() .withCookies(new Http.Cookie("foo", "1", 1000, "/", "example.com", false, true, null)); @@ -374,7 +373,7 @@ public void getOptionalCookie() { } @Test - public void redirectShouldReturnTheSameUrlIfTheQueryStringParamsMapIsEmpty() { + void redirectShouldReturnTheSameUrlIfTheQueryStringParamsMapIsEmpty() { Map> queryStringParameters = new HashMap<>(); String url = "/somewhere"; Result result = Results.redirect(url, queryStringParameters); @@ -383,7 +382,7 @@ public void redirectShouldReturnTheSameUrlIfTheQueryStringParamsMapIsEmpty() { } @Test - public void redirectAppendGivenQueryStringParamsToTheUrlIfUrlContainsQuestionMark() { + void redirectAppendGivenQueryStringParamsToTheUrlIfUrlContainsQuestionMark() { Map> queryStringParameters = new HashMap<>(); queryStringParameters.put("param1", Arrays.asList("value1")); String url = "/somewhere?param2=value2"; @@ -396,7 +395,7 @@ public void redirectAppendGivenQueryStringParamsToTheUrlIfUrlContainsQuestionMar } @Test - public void redirectShouldAddQueryStringParamsToTheUrl() { + void redirectShouldAddQueryStringParamsToTheUrl() { Map> queryStringParameters = new HashMap<>(); queryStringParameters.put("param1", Arrays.asList("value1")); queryStringParameters.put("param2", Arrays.asList("value2")); diff --git a/core/play/src/test/java/play/mvc/SecurityTest.java b/core/play/src/test/java/play/mvc/SecurityTest.java index a5105a36836..8e173adf388 100644 --- a/core/play/src/test/java/play/mvc/SecurityTest.java +++ b/core/play/src/test/java/play/mvc/SecurityTest.java @@ -16,9 +16,9 @@ import org.junit.jupiter.api.Test; import play.inject.Injector; -public class SecurityTest { +class SecurityTest { @Test - public void testAuthorized() throws Exception { + void testAuthorized() throws Exception { Http.RequestBuilder builder = new Http.RequestBuilder(); builder.session("username", "test_user"); @@ -35,7 +35,7 @@ public void testAuthorized() throws Exception { } @Test - public void testUnauthorized() throws Exception { + void testUnauthorized() throws Exception { Result r = callWithSecurity( new Http.RequestBuilder().build(), diff --git a/documentation/manual/working/javaGuide/main/async/code/javaguide/async/JavaAsync.java b/documentation/manual/working/javaGuide/main/async/code/javaguide/async/JavaAsync.java index 5cee9a58574..b666f12741b 100644 --- a/documentation/manual/working/javaGuide/main/async/code/javaguide/async/JavaAsync.java +++ b/documentation/manual/working/javaGuide/main/async/code/javaguide/async/JavaAsync.java @@ -18,7 +18,7 @@ import play.libs.concurrent.*; import play.mvc.Result; -public class JavaAsync { +class JavaAsync { @Test void promiseWithTimeout() throws Exception { @@ -64,7 +64,7 @@ public CompletionStage delayedResult() { } @Test - public void promisePi() throws Exception { + void promisePi() throws Exception { // #promise-pi CompletionStage promiseOfPIValue = computePIAsynchronously(); // Runs in same thread @@ -75,7 +75,7 @@ public void promisePi() throws Exception { } @Test - public void promiseAsync() throws Exception { + void promiseAsync() throws Exception { // #promise-async // creates new task CompletionStage promiseOfInt = diff --git a/documentation/manual/working/javaGuide/main/forms/code/javaguide/forms/JavaForms.java b/documentation/manual/working/javaGuide/main/forms/code/javaguide/forms/JavaForms.java index 3f6333bcec3..e001b5eef07 100644 --- a/documentation/manual/working/javaGuide/main/forms/code/javaguide/forms/JavaForms.java +++ b/documentation/manual/working/javaGuide/main/forms/code/javaguide/forms/JavaForms.java @@ -380,7 +380,7 @@ class User extends javaguide.forms.u1.User { } @Test - public void dynamicForm() { + void dynamicForm() { Result result = call( new Controller3(app.injector().instanceOf(JavaHandlerComponents.class)), diff --git a/documentation/manual/working/javaGuide/main/ws/code/javaguide/ws/StandaloneWithConfig.java b/documentation/manual/working/javaGuide/main/ws/code/javaguide/ws/StandaloneWithConfig.java index 184bf5810db..cb845434347 100644 --- a/documentation/manual/working/javaGuide/main/ws/code/javaguide/ws/StandaloneWithConfig.java +++ b/documentation/manual/working/javaGuide/main/ws/code/javaguide/ws/StandaloneWithConfig.java @@ -19,10 +19,10 @@ import play.shaded.ahc.org.asynchttpclient.DefaultAsyncHttpClient; import play.shaded.ahc.org.asynchttpclient.DefaultAsyncHttpClientConfig; -public class StandaloneWithConfig { +class StandaloneWithConfig { @Test - public void testMe() throws IOException { + void testMe() throws IOException { // #ws-standalone-with-config // Set up Akka String name = "wsclient"; diff --git a/persistence/play-java-jdbc/src/test/java/play/db/DatabaseTest.java b/persistence/play-java-jdbc/src/test/java/play/db/DatabaseTest.java index 87284868177..e7df3e65f2b 100644 --- a/persistence/play-java-jdbc/src/test/java/play/db/DatabaseTest.java +++ b/persistence/play-java-jdbc/src/test/java/play/db/DatabaseTest.java @@ -15,10 +15,10 @@ import org.junit.jupiter.api.Test; import play.api.libs.JNDI; -public class DatabaseTest { +class DatabaseTest { @Test - public void createDatabase() { + void createDatabase() { Database db = Databases.createFrom("test", "org.h2.Driver", "jdbc:h2:mem:test"); assertEquals("test", db.getName()); assertEquals("jdbc:h2:mem:test", db.getUrl()); @@ -26,7 +26,7 @@ public void createDatabase() { } @Test - public void createDefaultDatabase() { + void createDefaultDatabase() { Database db = Databases.createFrom("org.h2.Driver", "jdbc:h2:mem:default"); assertEquals("default", db.getName()); assertEquals("jdbc:h2:mem:default", db.getUrl()); @@ -34,7 +34,7 @@ public void createDefaultDatabase() { } @Test - public void createConfiguredDatabase() throws Exception { + void createConfiguredDatabase() throws Exception { Map config = ImmutableMap.of("jndiName", "DefaultDS"); Database db = Databases.createFrom("test", "org.h2.Driver", "jdbc:h2:mem:test", config); assertEquals("test", db.getName()); @@ -48,7 +48,7 @@ public void createConfiguredDatabase() throws Exception { } @Test - public void createDefaultInMemoryDatabase() { + void createDefaultInMemoryDatabase() { Database db = Databases.inMemory(); assertEquals("default", db.getName()); assertEquals("jdbc:h2:mem:default", db.getUrl()); @@ -56,7 +56,7 @@ public void createDefaultInMemoryDatabase() { } @Test - public void createNamedInMemoryDatabase() { + void createNamedInMemoryDatabase() { Database db = Databases.inMemory("test"); assertEquals("test", db.getName()); assertEquals("jdbc:h2:mem:test", db.getUrl()); @@ -64,7 +64,7 @@ public void createNamedInMemoryDatabase() { } @Test - public void createInMemoryDatabaseWithUrlOptions() { + void createInMemoryDatabaseWithUrlOptions() { Map options = ImmutableMap.of("MODE", "MySQL"); Map config = ImmutableMap.of(); Database db = Databases.inMemory("test", options, config); @@ -76,7 +76,7 @@ public void createInMemoryDatabaseWithUrlOptions() { } @Test - public void createConfiguredInMemoryDatabase() throws Exception { + void createConfiguredInMemoryDatabase() throws Exception { Database db = Databases.inMemoryWith("jndiName", "DefaultDS"); assertEquals("default", db.getName()); assertEquals("jdbc:h2:mem:default", db.getUrl()); @@ -89,7 +89,7 @@ public void createConfiguredInMemoryDatabase() throws Exception { } @Test - public void supplyConnections() throws Exception { + void supplyConnections() throws Exception { Database db = Databases.inMemory("test-connection"); try (Connection connection = db.getConnection()) { @@ -102,7 +102,7 @@ public void supplyConnections() throws Exception { } @Test - public void enableAutocommitByDefault() throws Exception { + void enableAutocommitByDefault() throws Exception { Database db = Databases.inMemory("test-autocommit"); try (Connection c1 = db.getConnection(); @@ -118,7 +118,7 @@ public void enableAutocommitByDefault() throws Exception { } @Test - public void provideConnectionHelpers() { + void provideConnectionHelpers() { Database db = Databases.inMemory("test-withConnection"); db.withConnection( @@ -142,7 +142,7 @@ public void provideConnectionHelpers() { } @Test - public void provideConnectionHelpersWithAutoCommitIsFalse() { + void provideConnectionHelpersWithAutoCommitIsFalse() { Database db = Databases.inMemory("test-withConnection(autoCommit = false"); db.withConnection( @@ -166,7 +166,7 @@ public void provideConnectionHelpersWithAutoCommitIsFalse() { } @Test - public void provideTransactionHelper() { + void provideTransactionHelper() { Database db = Databases.inMemory("test-withTransaction"); boolean created = @@ -208,7 +208,7 @@ public void provideTransactionHelper() { } @Test - public void notSupplyConnectionsAfterShutdown() throws Exception { + void notSupplyConnectionsAfterShutdown() throws Exception { Database db = Databases.inMemory("test-shutdown"); db.getConnection().close(); db.shutdown(); @@ -217,7 +217,7 @@ public void notSupplyConnectionsAfterShutdown() throws Exception { } @Test - public void useConnectionPoolDataSourceProxyWhenLogSqlIsTrue() throws Exception { + void useConnectionPoolDataSourceProxyWhenLogSqlIsTrue() throws Exception { Map config = ImmutableMap.of("jndiName", "DefaultDS", "logSql", "true"); Database db = Databases.createFrom("test", "org.h2.Driver", "jdbc:h2:mem:test", config); assertInstanceOf(ConnectionPoolDataSourceProxy.class, db.getDataSource()); @@ -227,7 +227,7 @@ public void useConnectionPoolDataSourceProxyWhenLogSqlIsTrue() throws Exception } @Test - public void manualSetupTransactionIsolationLevel() throws Exception { + void manualSetupTransactionIsolationLevel() throws Exception { Database db = Databases.inMemory("test-withTransaction"); boolean created = diff --git a/persistence/play-java-jdbc/src/test/java/play/db/NamedDatabaseTest.java b/persistence/play-java-jdbc/src/test/java/play/db/NamedDatabaseTest.java index ac3981cf25c..496d7c6e471 100644 --- a/persistence/play-java-jdbc/src/test/java/play/db/NamedDatabaseTest.java +++ b/persistence/play-java-jdbc/src/test/java/play/db/NamedDatabaseTest.java @@ -18,10 +18,10 @@ import play.inject.guice.GuiceApplicationBuilder; import play.inject.guice.GuiceApplicationLoader; -public class NamedDatabaseTest { +class NamedDatabaseTest { @Test - public void bindDatabasesByName() { + void bindDatabasesByName() { Map config = ImmutableMap.of( "db.default.driver", @@ -46,7 +46,7 @@ private Injector createInjector(Map config) { } @Test - public void notBindDefaultDatabaseWithoutConfiguration() { + void notBindDefaultDatabaseWithoutConfiguration() { Map config = ImmutableMap.of("db.other.driver", "org.h2.Driver", "db.other.url", "jdbc:h2:mem:other"); Injector injector = createInjector(config); @@ -57,7 +57,7 @@ public void notBindDefaultDatabaseWithoutConfiguration() { } @Test - public void notBindNamedDefaultDatabaseWithoutConfiguration() { + void notBindNamedDefaultDatabaseWithoutConfiguration() { Map config = ImmutableMap.of("db.other.driver", "org.h2.Driver", "db.other.url", "jdbc:h2:mem:other"); Injector injector = createInjector(config); @@ -68,7 +68,7 @@ public void notBindNamedDefaultDatabaseWithoutConfiguration() { } @Test - public void allowDefaultDatabaseNameToBeConfigured() { + void allowDefaultDatabaseNameToBeConfigured() { Map config = ImmutableMap.of( "play.db.default", @@ -87,7 +87,7 @@ public void allowDefaultDatabaseNameToBeConfigured() { } @Test - public void allowDbConfigKeyToBeConfigured() { + void allowDbConfigKeyToBeConfigured() { Map config = ImmutableMap.of( "play.db.config", diff --git a/persistence/play-java-jpa/src/test/java/play/db/jpa/JPAApiTest.java b/persistence/play-java-jpa/src/test/java/play/db/jpa/JPAApiTest.java index c9e89ef88d0..81a6ab4a6c8 100644 --- a/persistence/play-java-jpa/src/test/java/play/db/jpa/JPAApiTest.java +++ b/persistence/play-java-jpa/src/test/java/play/db/jpa/JPAApiTest.java @@ -17,11 +17,11 @@ import play.db.Databases; import play.db.jpa.DefaultJPAConfig.JPAConfigProvider; -public class JPAApiTest { +class JPAApiTest { @RegisterExtension TestDatabaseExtension db = new TestDatabaseExtension(); @Test - public void shouldWorkWithEmptyConfiguration() { + void shouldWorkWithEmptyConfiguration() { String configString = ""; Set unitNames = getConfiguredPersistenceUnitNames(configString); assertTrue(unitNames.isEmpty()); @@ -35,28 +35,28 @@ private Set getConfiguredPersistenceUnitNames(String configString) { } @Test - public void shouldWorkWithSingleValue() { + void shouldWorkWithSingleValue() { String configString = "jpa.default = defaultPersistenceUnit"; Set unitNames = getConfiguredPersistenceUnitNames(configString); assertEquals(unitNames, new HashSet<>(List.of("defaultPersistenceUnit"))); } @Test - public void shouldWorkWithMultipleValues() { + void shouldWorkWithMultipleValues() { String configString = "jpa.default = defaultPersistenceUnit\n" + "jpa.number2 = number2Unit"; Set unitNames = getConfiguredPersistenceUnitNames(configString); assertEquals(unitNames, new HashSet<>(Arrays.asList("defaultPersistenceUnit", "number2Unit"))); } @Test - public void shouldWorkWithEmptyConfigurationAtConfiguredLocation() { + void shouldWorkWithEmptyConfigurationAtConfiguredLocation() { String configString = "play.jpa.config = myconfig.jpa"; Set unitNames = getConfiguredPersistenceUnitNames(configString); assertTrue(unitNames.isEmpty()); } @Test - public void shouldWorkWithSingleValueAtConfiguredLocation() { + void shouldWorkWithSingleValueAtConfiguredLocation() { String configString = "play.jpa.config = myconfig.jpa\n" + "myconfig.jpa.default = defaultPersistenceUnit"; Set unitNames = getConfiguredPersistenceUnitNames(configString); @@ -64,7 +64,7 @@ public void shouldWorkWithSingleValueAtConfiguredLocation() { } @Test - public void shouldWorkWithMultipleValuesAtConfiguredLocation() { + void shouldWorkWithMultipleValuesAtConfiguredLocation() { String configString = "play.jpa.config = myconfig.jpa\n" + "myconfig.jpa.default = defaultPersistenceUnit\n" @@ -74,13 +74,13 @@ public void shouldWorkWithMultipleValuesAtConfiguredLocation() { } @Test - public void shouldBeAbleToGetAnEntityManagerWithAGivenName() { + void shouldBeAbleToGetAnEntityManagerWithAGivenName() { EntityManager em = db.jpa.em("default"); assertNotNull(em); } @Test - public void shouldExecuteAFunctionBlockUsingAEntityManager() { + void shouldExecuteAFunctionBlockUsingAEntityManager() { db.jpa.withTransaction( entityManager -> { TestEntity entity = createTestEntity(); @@ -107,7 +107,7 @@ private TestEntity createTestEntity(Long id) { } @Test - public void shouldExecuteAFunctionBlockUsingASpecificNamedEntityManager() { + void shouldExecuteAFunctionBlockUsingASpecificNamedEntityManager() { db.jpa.withTransaction( "default", entityManager -> { @@ -124,7 +124,7 @@ public void shouldExecuteAFunctionBlockUsingASpecificNamedEntityManager() { } @Test - public void shouldExecuteAFunctionBlockAsAReadOnlyTransaction() { + void shouldExecuteAFunctionBlockAsAReadOnlyTransaction() { db.jpa.withTransaction( "default", true, @@ -142,7 +142,7 @@ public void shouldExecuteAFunctionBlockAsAReadOnlyTransaction() { } @Test - public void shouldExecuteASupplierBlockInsideATransaction() throws Exception { + void shouldExecuteASupplierBlockInsideATransaction() throws Exception { db.jpa.withTransaction( entityManager -> { TestEntity entity = createTestEntity(); @@ -157,7 +157,7 @@ public void shouldExecuteASupplierBlockInsideATransaction() throws Exception { } @Test - public void shouldNestTransactions() { + void shouldNestTransactions() { db.jpa.withTransaction( entityManager -> { TestEntity entity = new TestEntity(); @@ -178,7 +178,7 @@ public void shouldNestTransactions() { } @Test - public void shouldRollbackInnerTransactionOnly() { + void shouldRollbackInnerTransactionOnly() { db.jpa.withTransaction( entityManager -> { // Parent transaction creates entity 2 @@ -210,7 +210,7 @@ public void shouldRollbackInnerTransactionOnly() { } @Test - public void shouldRollbackOuterTransactionOnly() { + void shouldRollbackOuterTransactionOnly() { db.jpa.withTransaction( entityManager -> { // Parent transaction creates entity 2, but rolls back diff --git a/persistence/play-jdbc-evolutions/src/test/java/play/db/evolutions/EvolutionsTest.java b/persistence/play-jdbc-evolutions/src/test/java/play/db/evolutions/EvolutionsTest.java index 43380461ba2..cbfba3cd1ba 100644 --- a/persistence/play-jdbc-evolutions/src/test/java/play/db/evolutions/EvolutionsTest.java +++ b/persistence/play-jdbc-evolutions/src/test/java/play/db/evolutions/EvolutionsTest.java @@ -15,12 +15,12 @@ import play.db.Database; import play.db.Databases; -public class EvolutionsTest { +class EvolutionsTest { private Database database; private Connection connection; @Test - public void testEvolutions() throws Exception { + void testEvolutions() throws Exception { Evolutions.applyEvolutions( database, Evolutions.fromClassLoader(this.getClass().getClassLoader(), "evolutionstest/")); diff --git a/web/play-java-forms/src/test/java/play/mvc/HttpFormsTest.java b/web/play-java-forms/src/test/java/play/mvc/HttpFormsTest.java index ab3ed4809af..9d30022de86 100644 --- a/web/play-java-forms/src/test/java/play/mvc/HttpFormsTest.java +++ b/web/play-java-forms/src/test/java/play/mvc/HttpFormsTest.java @@ -32,7 +32,7 @@ * Tests for the Http class. This test is in the play-java project because we want to use some of * the play-java classes, e.g. the GuiceApplicationBuilder. */ -public class HttpFormsTest { +class HttpFormsTest { private static Config addLangs(Environment environment) { Config langOverrides = @@ -68,7 +68,7 @@ private Form copyFormWithoutRawData(final Form formToCopy, final Appli } @Test - public void testLangDataBinder() { + void testLangDataBinder() { withApplication( (app) -> { FormFactory formFactory = app.injector().instanceOf(FormFactory.class); @@ -136,7 +136,7 @@ public void testLangDataBinder() { } @Test - public void testLangDataBinderTransient() { + void testLangDataBinderTransient() { withApplication( (app) -> { FormFactory formFactory = app.injector().instanceOf(FormFactory.class); @@ -204,7 +204,7 @@ public void testLangDataBinderTransient() { } @Test - public void testLangErrorsAsJson() { + void testLangErrorsAsJson() { withApplication( (app) -> { MessagesApi messagesApi = app.injector().instanceOf(MessagesApi.class); @@ -243,7 +243,7 @@ public void testLangErrorsAsJson() { } @Test - public void testErrorsAsJsonWithEmptyMessages() { + void testErrorsAsJsonWithEmptyMessages() { withApplication( (app) -> { // The messagesApi is empty @@ -284,7 +284,7 @@ public void testErrorsAsJsonWithEmptyMessages() { } @Test - public void testLangAnnotationDateDataBinder() { + void testLangAnnotationDateDataBinder() { withApplication( (app) -> { FormFactory formFactory = app.injector().instanceOf(FormFactory.class); @@ -340,7 +340,7 @@ public void testLangAnnotationDateDataBinder() { } @Test - public void testLangAnnotationDateDataBinderTransient() { + void testLangAnnotationDateDataBinderTransient() { withApplication( (app) -> { FormFactory formFactory = app.injector().instanceOf(FormFactory.class); @@ -396,7 +396,7 @@ public void testLangAnnotationDateDataBinderTransient() { } @Test - public void testLangDateDataBinder() { + void testLangDateDataBinder() { withApplication( (app) -> { FormFactory formFactory = app.injector().instanceOf(FormFactory.class); @@ -467,7 +467,7 @@ public void testLangDateDataBinder() { } @Test - public void testLangDateDataBinderTransient() { + void testLangDateDataBinderTransient() { withApplication( (app) -> { FormFactory formFactory = app.injector().instanceOf(FormFactory.class); @@ -538,7 +538,7 @@ public void testLangDateDataBinderTransient() { } @Test - public void testInvalidMessages() { + void testInvalidMessages() { withApplication( (app) -> { FormFactory formFactory = app.injector().instanceOf(FormFactory.class); @@ -581,7 +581,7 @@ public void testInvalidMessages() { } @Test - public void testConstraintWithInjectedMessagesApi() { + void testConstraintWithInjectedMessagesApi() { withApplication( (app) -> { FormFactory formFactory = app.injector().instanceOf(FormFactory.class); diff --git a/web/play-java-forms/src/test/scala/play/data/format/FormattersTest.java b/web/play-java-forms/src/test/scala/play/data/format/FormattersTest.java index 0dc13f7cabd..223c273672d 100644 --- a/web/play-java-forms/src/test/scala/play/data/format/FormattersTest.java +++ b/web/play-java-forms/src/test/scala/play/data/format/FormattersTest.java @@ -16,7 +16,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; -public class FormattersTest { +class FormattersTest { private Formatters formatters; @@ -28,13 +28,13 @@ public void prepareFormatters() { } @Test - public void testFormattersParseUsingField() throws NoSuchFieldException { + void testFormattersParseUsingField() throws NoSuchFieldException { int integerFromPlainField = formatters.parse(Bean.class.getDeclaredField("plainIntegerField"), "10"); assertEquals(10, integerFromPlainField); } @Test - public void testFormattersParseUsingAnnotatedField() throws NoSuchFieldException { + void testFormattersParseUsingAnnotatedField() throws NoSuchFieldException { int integerFromAnnotatedField = formatters.parse(Bean.class.getDeclaredField("annotatedIntegerField"), "10"); assertEquals(15, integerFromAnnotatedField); } From bfafece08ca3956d8cca3ac4fbe5a70fea67011e Mon Sep 17 00:00:00 2001 From: "H. Habighorst" Date: Sat, 15 Jul 2023 10:49:34 +0200 Subject: [PATCH 14/15] #11839: fix wrong conversion (Before -> Before*Each*, After -> After*Each*, not all) --- .../java/play/libs/concurrent/FuturesTest.java | 4 ++-- .../javaguide/advanced/routing/JavaRoutingDsl.java | 8 ++++---- .../javaGuide/main/tests/JavaFunctionalTest.md | 6 ++++++ .../main/tests/JavaTestingWebServiceClients.md | 2 +- .../main/tests/JavaTestingWithDatabases.md | 6 ++++-- .../code/javaguide/test/junit5/DatabaseTest.java | 14 +++++++------- .../javaguide/test/junit5/GitHubClientTest.java | 12 ++++++------ .../test/junit5/JavaTestingWithDatabases.java | 14 +++++++------- 8 files changed, 37 insertions(+), 29 deletions(-) diff --git a/core/play/src/test/java/play/libs/concurrent/FuturesTest.java b/core/play/src/test/java/play/libs/concurrent/FuturesTest.java index 92af59dd057..d550bd194b5 100644 --- a/core/play/src/test/java/play/libs/concurrent/FuturesTest.java +++ b/core/play/src/test/java/play/libs/concurrent/FuturesTest.java @@ -23,13 +23,13 @@ class FuturesTest { private Futures futures; @BeforeEach - void setup() { + public void setup() { system = ActorSystem.create(); futures = new DefaultFutures(new play.api.libs.concurrent.DefaultFutures(system)); } @AfterEach - void teardown() { + public void teardown() { system.terminate(); futures = null; } diff --git a/documentation/manual/working/javaGuide/advanced/routing/code/javaguide/advanced/routing/JavaRoutingDsl.java b/documentation/manual/working/javaGuide/advanced/routing/code/javaguide/advanced/routing/JavaRoutingDsl.java index 1dba80743b4..149b8fa4b1b 100644 --- a/documentation/manual/working/javaGuide/advanced/routing/code/javaguide/advanced/routing/JavaRoutingDsl.java +++ b/documentation/manual/working/javaGuide/advanced/routing/code/javaguide/advanced/routing/JavaRoutingDsl.java @@ -4,7 +4,7 @@ package javaguide.advanced.routing; -import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; @@ -34,10 +34,10 @@ public class JavaRoutingDsl { @RegisterExtension static ApplicationExtension appExtension = new ApplicationExtension(fakeApplication()); static Application app = appExtension.getApplication(); - static RoutingDsl routingDsl; + private RoutingDsl routingDsl; - @BeforeAll - static void initializeRoutingDsl() { + @BeforeEach + public void initializeRoutingDsl() { routingDsl = app.injector().instanceOf(RoutingDsl.class); } diff --git a/documentation/manual/working/javaGuide/main/tests/JavaFunctionalTest.md b/documentation/manual/working/javaGuide/main/tests/JavaFunctionalTest.md index 21154da235b..6a962ad126d 100644 --- a/documentation/manual/working/javaGuide/main/tests/JavaFunctionalTest.md +++ b/documentation/manual/working/javaGuide/main/tests/JavaFunctionalTest.md @@ -49,6 +49,12 @@ Note that there are different ways to customize the `Application` creation when # [JUnit 4](https://junit.org/junit4/) Test Helpers +For backwards compatibility, the JUnit 4 helpers depend on JUnit 4. + +To simplify the migration from JUnit 4 to JUnit 5, one could convert the provided helpers to [JUnit 5 Vintage](https://junit.org/junit5/docs/current/user-guide/#migrating-from-junit4). + +This would allow a step by step migration to JUnit 5 without the dependency on JUnit 4. + ## Testing with an application To run JUnit 4 tests with an application, one can extend [`WithApplication`](api/java/play/test/junit4/WithApplication.html). diff --git a/documentation/manual/working/javaGuide/main/tests/JavaTestingWebServiceClients.md b/documentation/manual/working/javaGuide/main/tests/JavaTestingWebServiceClients.md index e2c91fa2372..3577f89f31d 100644 --- a/documentation/manual/working/javaGuide/main/tests/JavaTestingWebServiceClients.md +++ b/documentation/manual/working/javaGuide/main/tests/JavaTestingWebServiceClients.md @@ -36,7 +36,7 @@ To test this, we want an embedded Play server that will implement this endpoint. Our server is now running on a random port, that we can access through the `httpPort` method. We could build the base URL to pass to the `GitHubClient` using this, however Play has an even simpler mechanism. The [`WSTestClient`](api/java/play/test/WSTestClient.html) class provides a `newClient` method that takes in a port number. When requests are made using the client to relative URLs, eg to `/repositories`, this client will send that request to localhost on the passed in port. This means we can set a base URL on the `GitHubClient` to `""`. It also means if the client returns resources with URL links to other resources that the client then uses to make further requests, we can just ensure those a relative URLs and use them as is. -So now we can create a server, WS client and `GitHubClient` in a `@Before` annotated method, and shut them down in an `@After` annotated method, and then we can test the client in our tests: +So now we can create a server, WS client and `GitHubClient` in a `@BeforeEach` annotated method, and shut them down in an `@AfterEach` annotated method, and then we can test the client in our tests: @[content](code/javaguide/test/junit5/GitHubClientTest.java) diff --git a/documentation/manual/working/javaGuide/main/tests/JavaTestingWithDatabases.md b/documentation/manual/working/javaGuide/main/tests/JavaTestingWithDatabases.md index d679be8bf97..e4bbc1faf9b 100644 --- a/documentation/manual/working/javaGuide/main/tests/JavaTestingWithDatabases.md +++ b/documentation/manual/working/javaGuide/main/tests/JavaTestingWithDatabases.md @@ -26,10 +26,12 @@ After using a database, since the database is typically backed by a connection p @[shutdown](code/javaguide/test/junit5/JavaTestingWithDatabases.java) -These methods are particularly useful if you use them in combination with JUnit's `@Before` and `@After` annotations, for example: +These methods are particularly useful if you use them in combination with JUnit's `@BeforeEach` and `@AfterEach` annotations, for example: @[database-junit](code/javaguide/test/junit5/JavaTestingWithDatabases.java) +If the test database needs to be setup only once, e.g. all tests operate in a read-only matter, it is more efficient to use `@BeforeAll` and `@AfterAll` instead. + > **Tip:** You can use this to externalize your test database configuration, using environment variables or system properties to configure what database to use and how to connect to it. This allows for maximum flexibility for developers to have their own environments set up the way they please, as well as for CI systems that provide particular environments that may differ to development. ### Using an in-memory database @@ -80,6 +82,6 @@ This will load evolutions, in the same structure and format as is done for devel ### Integrating with JUnit -Typically you will have many tests that you want to run with the same evolutions, so it will make sense to extract the evolutions setup code into before and after methods, along with the database setup and tear down code. Here is what a complete test might look like: +Typically, you will have many tests that you want to run with the same evolutions, so it will make sense to extract the evolutions setup code into before and after methods, along with the database setup and tear down code. Here is what a complete test might look like: @[database-test](code/javaguide/test/junit5/DatabaseTest.java) diff --git a/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/DatabaseTest.java b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/DatabaseTest.java index d1751ce03ea..19a296da033 100644 --- a/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/DatabaseTest.java +++ b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/DatabaseTest.java @@ -8,8 +8,8 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.sql.Connection; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import play.db.Database; import play.db.Databases; @@ -18,10 +18,10 @@ class DatabaseTest { - static Database database; + private Database database; - @BeforeAll - static void setupDatabase() { + @BeforeEach + public void setupDatabase() { database = Databases.inMemory(); Evolutions.applyEvolutions( database, @@ -32,8 +32,8 @@ static void setupDatabase() { "drop table test;"))); } - @AfterAll - static void shutdownDatabase() { + @AfterEach + public void shutdownDatabase() { Evolutions.cleanupEvolutions(database); database.shutdown(); } diff --git a/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/GitHubClientTest.java b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/GitHubClientTest.java index 0dd004dd749..e72d961883e 100644 --- a/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/GitHubClientTest.java +++ b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/GitHubClientTest.java @@ -14,8 +14,8 @@ import java.io.IOException; import java.util.List; import java.util.concurrent.TimeUnit; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import play.libs.Json; import play.libs.ws.WSClient; @@ -27,8 +27,8 @@ class GitHubClientTest { private static WSClient ws; private static Server server; - @BeforeAll - static void setup() { + @BeforeEach + public void setup() { server = Server.forRouter( (components) -> @@ -48,8 +48,8 @@ static void setup() { client.baseUrl = ""; } - @AfterAll - static void tearDown() throws IOException { + @AfterEach + public void tearDown() throws IOException { try { ws.close(); } finally { diff --git a/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/JavaTestingWithDatabases.java b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/JavaTestingWithDatabases.java index 3c3e6c03208..6ae4e0d1d41 100644 --- a/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/JavaTestingWithDatabases.java +++ b/documentation/manual/working/javaGuide/main/tests/code/javaguide/test/junit5/JavaTestingWithDatabases.java @@ -10,8 +10,8 @@ import com.google.common.collect.ImmutableMap; import java.sql.Connection; import java.sql.SQLException; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import play.db.Database; import play.db.Databases; @@ -48,15 +48,15 @@ static class NotTested { static class ExampleUnitTest { // #database-junit - static Database database; + private Database database; - @BeforeAll - static void createDatabase() { + @BeforeEach + public void createDatabase() { database = Databases.createFrom("com.mysql.jdbc.Driver", "jdbc:mysql://localhost/test"); } - @AfterAll - static void shutdownDatabase() { + @AfterEach + public void shutdownDatabase() { database.shutdown(); } // #database-junit From 35017dcec1fab017edb00b58eccd6c151deee140 Mon Sep 17 00:00:00 2001 From: "H. Habighorst" Date: Sat, 15 Jul 2023 11:46:22 +0200 Subject: [PATCH 15/15] #11839: fix package dependencies --- build.sbt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.sbt b/build.sbt index 98ddedfb195..9b237bee310 100644 --- a/build.sbt +++ b/build.sbt @@ -204,7 +204,6 @@ lazy val PlayTestJUnit4Project = PlayCrossBuiltProject("Play-Test-JUnit4", "test mimaPreviousArtifacts := Set.empty, mimaFailOnNoPrevious := false, libraryDependencies ++= Seq(junit4, junit4Interface), - libraryDependencies --= Seq(junit5, junit5Interface), (Test / parallelExecution) := false ) .dependsOn( @@ -218,6 +217,7 @@ lazy val PlayTestJUnit4Project = PlayCrossBuiltProject("Play-Test-JUnit4", "test lazy val PlayTestJUnit5Project = PlayCrossBuiltProject("Play-Test-JUnit5", "testkit/play-test-junit5") .settings( + libraryDependencies ++= Seq(junit5, junit5Interface), mimaPreviousArtifacts := Set.empty, mimaFailOnNoPrevious := false, (Test / parallelExecution) := false,