### SQL Script Example Source: https://github.com/micronaut-projects/micronaut-test/blob/5.1.x/src/main/docs/guide/sql.adoc Example SQL scripts for setting up test data. ```sql CREATE TABLE products (id INT PRIMARY KEY, name VARCHAR(255)); INSERT INTO products (id, name) VALUES (1, 'Product 1'); INSERT INTO products (id, name) VALUES (2, 'Product 2'); ``` ```sql INSERT INTO products (id, name) VALUES (3, 'Product 3'); ``` -------------------------------- ### MathController Example Source: https://github.com/micronaut-projects/micronaut-test/blob/5.1.x/src/main/docs/guide/kotest/kotestMockingCollaborators.adoc This is an example of a MathController that uses MathService. ```kotlin package example.micronaut.kotest.mocking import io.micronaut.http.MediaType import io.micronaut.http.annotation.Controller import io.micronaut.http.annotation.Get @Controller("/math") open class MathController(private val mathService: MathService) { @Get("/compute/{number}", produces = [MediaType.TEXT_PLAIN]) fun compute(number: Long): String { return mathService.compute(number).toString() } } ``` -------------------------------- ### MathController Example Source: https://github.com/micronaut-projects/micronaut-test/blob/5.1.x/src/main/docs/guide/junit5/junit5MockingCollaborators.adoc This is an example of a MathController that uses MathService. ```java package import io.micronaut.http.MediaType; import io.micronaut.http.annotation.Controller; import io.micronaut.http.annotation.Get; import io.micronaut.http.annotation.Produces; @Controller("/math") public class MathController { private final MathService mathService; public MathController(MathService mathService) { this.mathService = mathService; } @Get(uri = "/compute/{number}", produces = MediaType.TEXT_PLAIN) @Produces(MediaType.TEXT_PLAIN) public Integer compute(int number) { return mathService.compute(number); } } ``` -------------------------------- ### Install and Use Type Pollution Agent in Tests Source: https://github.com/micronaut-projects/micronaut-test/blob/5.1.x/src/main/docs/guide/typePollution.adoc Install the ByteBuddy agent and set up a ThresholdFocusListener before each test. After the test, clear the listener and check if the focus event threshold was exceeded. This setup is crucial for detecting type pollution. ```java private static final int THRESHOLD = 10_000; private ThresholdFocusListener focusListener; @BeforeAll static void setupAgent() { TypePollutionTransformer.install(net.bytebuddy.agent.ByteBuddyAgent.install()); // <1> } @BeforeEach void setUp() { focusListener = new ThresholdFocusListener(); // <2> FocusListener.setFocusListener(focusListener); } @AfterEach void verifyNoTypeThrashing() { FocusListener.setFocusListener(null); // <4> Assertions.assertTrue(focusListener.checkThresholds(THRESHOLD), "Threshold exceeded, check logs."); } @Test public void sample() { // <3> Object c = new Concrete(); int j = 0; for (int i = 0; i < THRESHOLD * 2; i++) { if (c instanceof A) { j++; } if (c instanceof B) { j++; } } System.out.println(j); } interface A { // <5> } interface B { } static class Concrete implements A, B { } ``` -------------------------------- ### MathController Example Source: https://github.com/micronaut-projects/micronaut-test/blob/5.1.x/src/main/docs/guide/spock/spockUsingCollaborators.adoc A sample Micronaut controller that uses a MathService collaborator. ```groovy package example.micronaut.test.spock import io.micronaut.http.annotation.Controller import io.micronaut.http.annotation.Get @Controller("/math") class MathController { private final MathService mathService MathController(MathService mathService) { this.mathService = mathService } @Get("/compute/{number}") Integer compute(@Parameter Integer number) { mathService.compute(number) } } ``` -------------------------------- ### Starting Embedded Server in Spock Source: https://github.com/micronaut-projects/micronaut-test/blob/5.1.x/src/main/docs/guide/introduction.adoc Demonstrates how to start an embedded Micronaut server for testing in Spock. The `@Shared` annotation ensures the server starts only once for all test methods, and `@AutoCleanup` handles server shutdown after the test suite. ```groovy @Shared // <1> @AutoCleanup // <2> EmbeddedServer embeddedServer = ApplicationContext.run(EmbeddedServer) ``` -------------------------------- ### Using propertySources with @MicronautTest in Kotest Source: https://github.com/micronaut-projects/micronaut-test/blob/5.1.x/src/main/docs/guide/kotest/kotestDefiningAdditionalTestSpecificProperties.adoc Shows how to configure test-specific properties by referencing external property source files via the @MicronautTest annotation. The example expects `myprops.properties` in `src/test/resources/io/micronaut/kotest/`. ```kotlin package io.micronaut.kotest import io.micronaut.context.annotation.PropertySource import io.micronaut.test.kotest.MicronautKotest import io.kotest.core.spec.style.BehaviorSpec @MicronautKotest @PropertySource(value = ["classpath:io/micronaut/kotest/myprops.properties"]) class PropertySourceTest { @BehaviorSpec init { "test properties" .config("my.prop.one") { "should be value one" it(my.prop.one) shouldBe "value one" } .config("my.prop.two") { "should be value two" it(my.prop.two) shouldBe "value two" } } } ``` -------------------------------- ### REST-assured Example Source: https://github.com/micronaut-projects/micronaut-test/blob/5.1.x/src/main/docs/guide/restAssured.adoc Injecting and using RequestSpecification in a Micronaut test. Ensure the micronaut-test-rest-assured dependency is added to your project. ```java include::{restassuredtests}/RestAssuredHelloWorldTest.java[] ``` -------------------------------- ### Using `micronaut.test.server.executable` Property Source: https://github.com/micronaut-projects/micronaut-test/blob/5.1.x/src/main/docs/guide/junit5/junit5TestingExternalServers.adoc Configure Micronaut to start an external server executable for the test lifecycle. This replaces the regular server with an instance that executes the process and closes it when the test ends. ```java package example.micronaut.test.server; import io.micronaut.http.client.HttpClient; import io.micronaut.http.client.annotation.Client; import io.micronaut.test.extensions.junit5.annotation.MicronautTest; import org.junit.jupiter.api.Test; import jakarta.inject.Inject; import static org.junit.jupiter.api.Assertions.assertTrue; @MicronautTest(property = { "micronaut.test.server.executable=src/test/resources/server.jar" }) class ProcessServerTest { @Inject @Client("/") HttpClient client; @Test void testProcessServer() throws Exception { assertTrue(client.toBlocking().exchange("/", String.class).getBody().isPresent()); } } ``` -------------------------------- ### Set Single Transaction Mode for a Test Source: https://github.com/micronaut-projects/micronaut-test/blob/5.1.x/src/main/docs/guide/includes/transaction.adoc Configure a test to use `TransactionMode.SINGLE_TRANSACTION` to wrap setup, test, and cleanup methods within a single transaction. ```java @MicronautTest(transactionMode = TransactionMode.SINGLE_TRANSACTION) ``` -------------------------------- ### Implementing TestPropertyProvider Interface Source: https://github.com/micronaut-projects/micronaut-test/blob/5.1.x/src/main/docs/guide/junit5/junit5DefiningAdditionalTestSpecificProperties.adoc Implement the TestPropertyProvider interface for dynamic property definition, especially when setup is required. Ensure your test uses JUnit's PER_CLASS test instance lifecycle. ```java import io.micronaut.test.junit5.PropertySourceMapTest; import io.micronaut.test.support.TestPropertyProvider; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.api.extension.ExtendWith; import java.util.Map; @ExtendWith(PropertySourceMapTest.class) @TestInstance(TestInstance.Lifecycle.PER_CLASS) public class PropertySourceMapTest implements TestPropertyProvider { @Override public Map getProperties() { // Perform setup and return properties return Map.of("my.dynamic.property", "dynamicValue"); } @Test void testDynamicProperty() { // ... test logic using dynamic properties } @org.junit.jupiter.api.extension.RegisterExtension static final PropertySourceMapTest propertySourceMapTest = new PropertySourceMapTest(); @Test void testAnotherThing() { // ... } } ``` -------------------------------- ### Spock Test Example for Micronaut Source: https://github.com/micronaut-projects/micronaut-test/blob/5.1.x/README.md Demonstrates a Spock test with Micronaut Test. Uses @MicronautTest for application context and @Inject for dependency injection. Features parameterized tests with @Unroll and a 'where' block for data. ```groovy import io.micronaut.test.annotation.MicronautTest import spock.lang.* import jakarta.inject.Inject @MicronautTest // Declares the test as a micronaut test class MathServiceSpec extends Specification { @Inject MathService mathService // Dependency injection is used to supply the system under test @Unroll void "should compute #num times 4"() { // This is the test case. #num will be replaced by the values defined in the where: block when: def result = mathService.compute(num) then: result == expected where: num | expected 2 | 8 3 | 12 } } ``` -------------------------------- ### JUnit 5 Test Example for Micronaut Source: https://github.com/micronaut-projects/micronaut-test/blob/5.1.x/README.md Illustrates a JUnit 5 test for Micronaut applications. It utilizes @MicronautTest to enable the Micronaut testing context and @Inject for dependency injection. Parameterized tests are configured using @ParameterizedTest and @CsvSource. ```java import io.micronaut.test.annotation.MicronautTest; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import jakarta.inject.Inject; @MicronautTest // Declares the test as a micronaut test class MathServiceTest { @Inject MathService mathService; // Dependency injection is used to supply the system under test @ParameterizedTest @CsvSource({"2,8", "3,12"}) void testComputeNumToSquare(Integer num, Integer square) { final Integer result = mathService.compute(num); // Injected bean can be used in test case Assertions.assertEquals( square, result ); } } ``` -------------------------------- ### Using propertySources in @MicronautTest Source: https://github.com/micronaut-projects/micronaut-test/blob/5.1.x/src/main/docs/guide/junit5/junit5DefiningAdditionalTestSpecificProperties.adoc Specify additional property sources in supported formats (YAML, JSON, Java properties) using the @MicronautTest annotation. The example expects 'myprops.properties' in src/test/resources/io/micronaut/junit5/. ```java import io.micronaut.test.junit5.PropertySourceTest; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @ExtendWith(PropertySourceTest.class) @io.micronaut.test.annotation.MicronautTest(propertySources = "classpath:io/micronaut/junit5/myprops.properties") public class PropertySourceTest { @Test void testPropertySource() { // ... test logic using properties from myprops.properties } @org.junit.jupiter.api.extension.RegisterExtension static final PropertySourceTest propertySourceTest = new PropertySourceTest(); @Test void testSomethingElse() { // ... } } ``` -------------------------------- ### Using HttpClient with Eager Initialization Source: https://github.com/micronaut-projects/micronaut-test/blob/5.1.x/src/main/docs/guide/introduction.adoc Illustrates how to obtain an `HttpClient` in a test when eager singleton initialization is enabled. It involves injecting `EmbeddedServer`, creating a `Supplier` for the `HttpClient`, and then using the `Supplier` to make requests. ```java include::test-junit5/src/test/java/io/micronaut/test/junit5/EagerInitializationTest.java[tags=eager, indent=0] ``` -------------------------------- ### MathService Implementation Source: https://github.com/micronaut-projects/micronaut-test/blob/5.1.x/src/main/docs/guide/spock/writingAMicronautTestWithSpock.adoc A simple Micronaut bean implementation of the MathService. ```groovy package example.micronaut.spock import io.micronaut.context.annotation.Bean @Bean class MathServiceImpl implements MathService { @Override int compute(int value) { return value * 4 } } ``` -------------------------------- ### Annotate Test Class with SQL Scripts (Kotlin) Source: https://github.com/micronaut-projects/micronaut-test/blob/5.1.x/src/main/docs/guide/sql.adoc Annotate a test class to execute SQL scripts before tests run. The default phase is BEFORE_CLASS. ```kotlin @MicronautTest @SqlGroup( Sql(value = "classpath:create.sql", phase = Sql.Phase.BEFORE_CLASS), Sql(value = "classpath:datasource_1_insert.sql", phase = Sql.Phase.BEFORE_CLASS) ) class SqlDatasourceTest { @Test fun `test sql datasource`() { // test logic } } ``` -------------------------------- ### Annotate Test Class with SQL Scripts (Groovy) Source: https://github.com/micronaut-projects/micronaut-test/blob/5.1.x/src/main/docs/guide/sql.adoc Annotate a test class to execute SQL scripts before tests run. The default phase is BEFORE_CLASS. ```groovy @MicronautTest @SqlGroup( @Sql(value = "classpath:create.sql", phase = Sql.Phase.BEFORE_CLASS), @Sql(value = "classpath:datasource_1_insert.sql", phase = Sql.Phase.BEFORE_CLASS) ) class SqlDatasourceSpec { @Test void "test sql datasource"() { // test logic } } ``` -------------------------------- ### Configure Kotest ProjectConfig for Micronaut Test Source: https://github.com/micronaut-projects/micronaut-test/blob/5.1.x/src/main/docs/guide/kotest/kotestBeforeYouBegin.adoc Provide a `ProjectConfig` to inform Kotest of the Micronaut extensions. This is required before writing tests. ```kotlin package io.micronaut.test.kotest5 import io.kotest.core.config.AbstractProjectConfig import io.micronaut.test.kotest5.MicronautKotestExtension object ProjectConfig : AbstractProjectConfig() { override val extensions = mutableListOf(MicronautKotestExtension) } ``` -------------------------------- ### Annotate Test Class with SQL Scripts (Java) Source: https://github.com/micronaut-projects/micronaut-test/blob/5.1.x/src/main/docs/guide/sql.adoc Annotate a test class to execute SQL scripts before tests run. The default phase is BEFORE_CLASS. ```java @MicronautTest @SqlGroup( @Sql(value = "classpath:create.sql", phase = Sql.Phase.BEFORE_CLASS), @Sql(value = "classpath:datasource_1_insert.sql", phase = Sql.Phase.BEFORE_CLASS) ) class SqlDatasourceTest { @Test void "test sql datasource"() { // test logic } } ``` -------------------------------- ### MathService Implementation Source: https://github.com/micronaut-projects/micronaut-test/blob/5.1.x/src/main/docs/guide/kotest/kotestWritingAMicronautTest.adoc A Micronaut bean implementation of the MathService interface that multiplies the input value by 4. ```kotlin package example.micronaut.kotest import io.micronaut.context.annotation.Bean @Bean class MathServiceImpl : MathService { override fun compute(value: Int): Int { return value * 4 } } ``` -------------------------------- ### Specify Packages for Classpath Scanning Source: https://github.com/micronaut-projects/micronaut-test/blob/5.1.x/src/main/docs/guide/includes/environments-classpath-scanning.adoc Alternatively, provide packages to be scanned by integrations using the `packages` argument in `@MicronautTest`. ```java @MicronautTest(packages="foo.bar") ``` -------------------------------- ### Specify Application Class for Classpath Scanning Source: https://github.com/micronaut-projects/micronaut-test/blob/5.1.x/src/main/docs/guide/includes/environments-classpath-scanning.adoc When integrations require classpath scanning, specify the application class using the `application` argument in `@MicronautTest`. ```java @MicronautTest(application=Application.class) ``` -------------------------------- ### Maven Surefire Plugin Configuration for JUnit Platform Source: https://github.com/micronaut-projects/micronaut-test/blob/5.1.x/src/main/docs/guide/kotest/settingUpKoTest.adoc Configure the Maven Surefire plugin in your pom.xml to utilize the JUnit 5 platform for running tests with Kotest. ```xml org.apache.maven.plugins maven-surefire-plugin 2.22.2 org.junit.jupiter junit-jupiter-engine 5.6.2 ``` -------------------------------- ### MathService Implementation Source: https://github.com/micronaut-projects/micronaut-test/blob/5.1.x/src/main/docs/guide/junit5/writingAMicronautTestWithJUnit5.adoc Provides a Micronaut bean implementation for the MathService interface. ```java package example.micronaut.test; import io.micronaut.context.annotation.Bean; @Bean public class MathServiceImpl implements MathService { @Override public int compute(int value) { return value * 4; } } ``` -------------------------------- ### Gradle Dependencies for Kotest Source: https://github.com/micronaut-projects/micronaut-test/blob/5.1.x/src/main/docs/guide/kotest/settingUpKoTest.adoc Add these dependencies to your build.gradle file to integrate Kotest with Micronaut. Includes necessary testing and mocking libraries. ```groovy dependencies { kaptTest "io.micronaut:micronaut-inject-java" testImplementation "io.micronaut.test:micronaut-test-kotest5" testImplementation "io.mockk:mockk:{mockkVersion}" testImplementation "io.kotest:kotest-runner-junit6-jvm:{kotestVersion}" } // use JUnit 5 platform test { useJUnitPlatform() } ``` -------------------------------- ### Using Property Sources in Files Source: https://github.com/micronaut-projects/micronaut-test/blob/5.1.x/src/main/docs/guide/spock/definingAdditionalTestSpecificProperties.adoc Specify additional property sources in various formats (YAML, JSON, Java properties) using the @MicronautTest annotation. This allows for externalized configuration for tests. ```groovy include::{spocktests}/PropertySourceSpec.groovy[] ``` -------------------------------- ### Annotate Test Class with SQL Scripts for Named Datasource (Kotlin) Source: https://github.com/micronaut-projects/micronaut-test/blob/5.1.x/src/main/docs/guide/sql.adoc Specify the datasource name when using multiple datasources to execute SQL scripts. ```kotlin @MicronautTest @SqlGroup( Sql(value = "classpath:create.sql", datasource = "users", phase = Sql.Phase.BEFORE_CLASS), Sql(value = "classpath:datasource_1_insert.sql", datasource = "users", phase = Sql.Phase.BEFORE_CLASS) ) class SqlNamedDatasourceTest { @Test fun `test sql datasource`() { // test logic } } ``` -------------------------------- ### Annotate Test Class with SQL Scripts for Named Datasource (Groovy) Source: https://github.com/micronaut-projects/micronaut-test/blob/5.1.x/src/main/docs/guide/sql.adoc Specify the datasource name when using multiple datasources to execute SQL scripts. ```groovy @MicronautTest @SqlGroup( @Sql(value = "classpath:create.sql", datasource = "users", phase = Sql.Phase.BEFORE_CLASS), @Sql(value = "classpath:datasource_1_insert.sql", datasource = "users", phase = Sql.Phase.BEFORE_CLASS) ) class SqlNamedDatasourceSpec { @Test void "test sql datasource"() { // test logic } } ``` -------------------------------- ### MathService Interface Source: https://github.com/micronaut-projects/micronaut-test/blob/5.1.x/src/main/docs/guide/spock/writingAMicronautTestWithSpock.adoc Defines the contract for the MathService. ```groovy package example.micronaut.spock interface MathService { int compute(int value) } ``` -------------------------------- ### MathService Interface Source: https://github.com/micronaut-projects/micronaut-test/blob/5.1.x/src/main/docs/guide/kotest/kotestWritingAMicronautTest.adoc Defines the contract for a service that performs mathematical operations. ```kotlin package example.micronaut.kotest interface MathService { fun compute(value: Int): Int } ``` -------------------------------- ### Specify Test Environments with @MicronautTest Source: https://github.com/micronaut-projects/micronaut-test/blob/5.1.x/src/main/docs/guide/includes/environments-classpath-scanning.adoc Use the `environments` argument in `@MicronautTest` to define the environment names for your tests. ```java @MicronautTest(environments={"foo", "bar"}) ``` -------------------------------- ### Maven Dependencies for Kotest Source: https://github.com/micronaut-projects/micronaut-test/blob/5.1.x/src/main/docs/guide/kotest/settingUpKoTest.adoc Configure your pom.xml with these dependencies to use Kotest for testing in a Micronaut project. Ensure to include testing and mocking libraries. ```xml io.micronaut.test micronaut-test-kotest5 {version} test io.mockk mockk {mockkVersion} test io.kotest kotest-runner-junit6-jvm {kotestVersion} test ``` -------------------------------- ### Injecting EmbeddedServer and ApplicationContext Source: https://github.com/micronaut-projects/micronaut-test/blob/5.1.x/src/main/docs/guide/introduction.adoc Shows how to inject `EmbeddedServer` and `ApplicationContext` directly into a test class when using `@MicronautTest`. This avoids the need to declare them as shared properties. ```groovy @Inject EmbeddedServer server //refers to the server that was started up for this test suite @Inject ApplicationContext context //refers to the current application context within the scope of the test ``` -------------------------------- ### Annotate Test Class with SQL Scripts for Named Datasource (Java) Source: https://github.com/micronaut-projects/micronaut-test/blob/5.1.x/src/main/docs/guide/sql.adoc Specify the datasource name when using multiple datasources to execute SQL scripts. ```java @MicronautTest @SqlGroup( @Sql(value = "classpath:create.sql", datasource = "users", phase = Sql.Phase.BEFORE_CLASS), @Sql(value = "classpath:datasource_1_insert.sql", datasource = "users", phase = Sql.Phase.BEFORE_CLASS) ) class SqlNamedDatasourceTest { @Test void "test sql datasource"() { // test logic } } ``` -------------------------------- ### Add JUnit 5 Dependencies (Gradle) Source: https://github.com/micronaut-projects/micronaut-test/blob/5.1.x/src/main/docs/guide/junit5/settingUpJUnit5.adoc Include these dependencies in your build.gradle file to enable JUnit 5 testing with Micronaut. Ensure you also configure the test task to use the JUnit 5 platform. ```groovy dependencies { testAnnotationProcessor "io.micronaut:micronaut-inject-java" ... testImplementation("org.junit.jupiter:junit-jupiter-api") testImplementation("io.micronaut.test:micronaut-test-junit5") testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine") testImplementation("org.junit.jupiter:junit-jupiter-engine") } // use JUnit 5 platform test { useJUnitPlatform() } ``` -------------------------------- ### MathService Spock Specification Source: https://github.com/micronaut-projects/micronaut-test/blob/5.1.x/src/main/docs/guide/spock/writingAMicronautTestWithSpock.adoc Tests the MathService implementation using Spock and Micronaut's testing support. ```groovy package example.micronaut.spock import io.micronaut.test.extensions.spock.annotation.MicronautTest import jakarta.inject.Inject import spock.lang.Specification @MicronautTest class MathServiceSpec extends Specification { @Inject MathService mathService def "compute should return value times 4"() { expect: mathService.compute(5) == 20 } } ``` -------------------------------- ### Execute SQL Script After Each Test (Java) Source: https://github.com/micronaut-projects/micronaut-test/blob/5.1.x/src/main/docs/guide/sql.adoc Specify the phase attribute to run SQL scripts after each test method. ```java @Sql(value = "classpath:delete.sql", phase = Sql.Phase.AFTER_METHOD) void testSomething() { // ... } ``` -------------------------------- ### Maven Kotlin Plugin Configuration for Micronaut Source: https://github.com/micronaut-projects/micronaut-test/blob/5.1.x/src/main/docs/guide/kotest/settingUpKoTest.adoc Configure the Kotlin Maven plugin in your pom.xml for Micronaut projects using Kotest. This includes setting up compiler plugins and annotation processors. ```xml kotlin-maven-plugin org.jetbrains.kotlin 1.4.10 all-open kapt kapt ${project.baseDir}/src/main/kotlin io.micronaut micronaut-inject-java ${micronaut.version} io.micronaut micronaut-validation ${micronaut.version} compile compile ${project.basedir}/src/main/kotlin ${project.basedir}/src/main/java test-kapt test-kapt src/test/kotlin io.micronaut micronaut-inject-java ${micronaut.version} test-compile test-compile ${project.basedir}/src/test/kotlin ${project.basedir}/target/generated-sources/kapt/test org.jetbrains.kotlin kotlin-maven-allopen ${kotlinVersion} ``` -------------------------------- ### Add Spock Dependencies to Gradle Build Source: https://github.com/micronaut-projects/micronaut-test/blob/5.1.x/src/main/docs/guide/spock/settingUpSpock.adoc Include the Micronaut Test Spock and Spock Core dependencies in your Gradle build file. Ensure groovy-all is excluded from Spock Core if you are using a different Groovy version. ```groovy testImplementation "io.micronaut.test:micronaut-test-spock" testImplementation("org.spockframework:spock-core") { exclude group: "org.codehaus.groovy", module: "groovy-all" } ``` -------------------------------- ### Mocking Collaborator in Spock Test Source: https://github.com/micronaut-projects/micronaut-test/blob/5.1.x/src/main/docs/guide/spock/spockUsingCollaborators.adoc Tests interaction with a controller that uses a mocked collaborator (MathService). Uses @MockBean for the collaborator and HttpClient to invoke the controller. ```groovy package example.micronaut.test.spock import io.micronaut.http.client.HttpClient import io.micronaut.test.extensions.spock.annotation.MicronautTest import spock.lang.Specification import spock.lang.Shared import spock.lang.Subject import spock.lang.AutoCleanup import org.mockito.Mockito @MicronautTest class MathCollaboratorSpec extends Specification { @Shared @MockBean(MathService.class) MathService mathService = Mock(MathService) @AutoCleanup @Shared HttpClient httpClient void "test compute endpoint with mocked collaborator"() { when: def result = httpClient.toBlocking().retrieve("/math/compute/10", Integer) then: 1 * mathService.compute(10) >> 100 result == 100 } } ``` -------------------------------- ### MathService Kotest Specification Source: https://github.com/micronaut-projects/micronaut-test/blob/5.1.x/src/main/docs/guide/kotest/kotestWritingAMicronautTest.adoc A Kotest specification for testing the MathServiceImpl. It uses `@MicronautTest` to enable Micronaut's testing capabilities and injects the MathService bean for testing. ```groovy package example.micronaut.kotest import io.micronaut.test.extensions.kotest5.MicronautKotest import io.micronaut.test.annotation.MicronautTest import io.kotest.core.spec.style.BehaviorSpec @MicronautTest // <1> class MathServiceTest(private val mathService: MathService) : BehaviorSpec() { // <2> init { "MathService computation".config { "should compute the value times 4" { val result = mathService.compute(5) result shouldBe 20 // <3> } } } } ``` -------------------------------- ### Mocking Collaborators with JUnit 5 Source: https://github.com/micronaut-projects/micronaut-test/blob/5.1.x/src/main/docs/guide/junit5/junit5MockingCollaborators.adoc Tests interaction with a mock collaborator using `@MockBean` and `HttpClient`. The mock is injected into the test, and the controller uses a proxy pointing to the mock instance. The mock is refreshed for each test iteration. ```java package import io.micronaut.http.client.HttpClient; import io.micronaut.test.extensions.junit5.annotation.MicronautTest; import jakarta.inject.Inject; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Assertions; import static org.mockito.Mockito.*; @MicronautTest public class MathCollaboratorTest { @Inject HttpClient client; @MockBean(MathService.class) MathService mathService() { return mock(MathService.class); } @Test void testCompute() { // given: final int number = 1; final int result = 10; when(mathService().compute(number)).thenReturn(result); // when: final Integer value = client.toBlocking().retrieve("/math/compute/" + number, Integer.class); // then: Assertions.assertEquals(result, value); verify(mathService()).compute(number); } } ``` -------------------------------- ### R2DBC SQL Script Execution (Java) Source: https://github.com/micronaut-projects/micronaut-test/blob/5.1.x/src/main/docs/guide/sql.adoc For R2DBC, specify the resourceType as ConnectionFactory.class when using the @Sql annotation. ```java @MicronautTest @SqlGroup( @Sql(value = "classpath:create.sql", resourceType = ConnectionFactory.class, phase = Sql.Phase.BEFORE_CLASS) ) class MySqlConnectionTest { @Test void "test r2dbc connection"() { // test logic } } ``` -------------------------------- ### Conditionally Enable Test with @Requires Source: https://github.com/micronaut-projects/micronaut-test/blob/5.1.x/src/main/docs/guide/spock/usingRequiresOnTests.adoc This test will only run if the 'my-env' environment is active. You can activate environments by passing system properties like 'micronaut.environments'. ```java @MicronautTest @Requires(env = "my-env") class RequiresSpec extends Specification { ... } ``` -------------------------------- ### Using @Property Annotation in Kotest Source: https://github.com/micronaut-projects/micronaut-test/blob/5.1.x/src/main/docs/guide/kotest/kotestDefiningAdditionalTestSpecificProperties.adoc Demonstrates how to define test-specific properties directly within your test class using the @Property annotation. Ensure the `PropertyValueTest.kt` file is correctly included. ```kotlin package io.micronaut.kotest import io.micronaut.context.annotation.Property import io.micronaut.test.kotest.MicronautKotest import io.kotest.core.spec.style.BehaviorSpec @MicronautKotest class PropertyValueTest { @Property(name = "user.name", value = "micronaut") @Property(name = "user.age", value = "3") @BehaviorSpec init { "test properties" .config("user.name") { "should be micronaut" it(user.name) shouldBe "micronaut" } .config("user.age") { "should be 3" it(user.age) shouldBe "3" } } } ``` -------------------------------- ### Enable JUnit Leak Detection via System Property Source: https://github.com/micronaut-projects/micronaut-test/blob/5.1.x/src/main/docs/guide/nettyLeak.adoc Alternatively, enable JUnit Jupiter's extension auto-detection by setting the `junit.jupiter.extensions.autodetection.enabled` system property to `true`. This approach avoids manual extension registration in each test class. ```kotlin tasks { test { useJUnitPlatform() systemProperty("junit.jupiter.extensions.autodetection.enabled", "true") } } ``` -------------------------------- ### Add JUnit 5 Dependencies (Maven) Source: https://github.com/micronaut-projects/micronaut-test/blob/5.1.x/src/main/docs/guide/junit5/settingUpJUnit5.adoc Add these dependencies to your pom.xml to configure JUnit 5 testing within your Micronaut project. ```xml io.micronaut.test micronaut-test-junit5 test org.junit.jupiter junit-jupiter-api test org.junit.jupiter junit-jupiter-engine test ``` -------------------------------- ### Run Root Tests Concurrently in Kotest Source: https://github.com/micronaut-projects/micronaut-test/blob/5.1.x/src/main/docs/guide/kotest/Concurrency.adoc Enable concurrent execution of root tests within a Kotest spec by setting the TestExecutionMode to Concurrent. This can significantly reduce overall test execution time. ```kotlin import io.kotest.core.spec.style.StringSpec import io.kotest.engine.spec.tempfile.createTempFile import io.kotest.matchers.file.shouldExist import io.kotest.core.spec.TestExecutionMode class ConcurrentTestsSpec : StringSpec() { init { // This test will run concurrently with other root tests in this spec "a test that runs concurrently" { createTempFile("concurrent-test") }.config(testExecutionMode = TestExecutionMode.Concurrent) "another test that runs concurrently" { createTempFile("another-concurrent-test") }.config(testExecutionMode = TestExecutionMode.Concurrent) } } ``` -------------------------------- ### Define Mockk Mock Bean with @MockBean Source: https://github.com/micronaut-projects/micronaut-test/blob/5.1.x/src/main/docs/guide/kotest/usingMockkMocks.adoc Use the `@MockBean` annotation to define a method that returns a Mockk mock. The method's parameter specifies the type of bean to be replaced. This approach is useful for creating isolated mock beans for specific tests. ```kotlin import io.mockk.mockk import io.micronaut.context.annotation.MockBean import io.micronaut.test.extensions.kotest5.MicronautKotest5Extension import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(MicronautKotest5Extension::class) abstract class MathMockServiceTest { @MockBean fun mathService(): MathService { return mockk(relaxed = true) } @get:Inject abstract val mathService: MathService @Test fun `test math service`() { // given: // val mathService = getMock() // This is not needed with constructor injection // when: val result = mathService.multiply(2, 3) // then: // verify { // mathService.multiply(2, 3) // } assert(result == 6) } } ``` -------------------------------- ### MathService JUnit 5 Test Specification Source: https://github.com/micronaut-projects/micronaut-test/blob/5.1.x/src/main/docs/guide/junit5/writingAMicronautTestWithJUnit5.adoc Tests the MathService implementation using JUnit 5 and Micronaut's testing capabilities. The test is declared with @MicronautTest, and beans are injected using @Inject. ```groovy package example.micronaut.test import io.micronaut.test.extensions.junit5.annotation.MicronautTest import jakarta.inject.Inject import org.junit.jupiter.api.Test import static org.junit.jupiter.api.Assertions.assertEquals @MicronautTest class MathServiceTest { @Inject MathService mathService @Test void testCompute() { assertEquals(8, mathService.compute(2)) } } ``` -------------------------------- ### Define a Spock Mock Bean with @MockBean Source: https://github.com/micronaut-projects/micronaut-test/blob/5.1.x/src/main/docs/guide/spock/usingSpockMocks.adoc Use the `@MockBean` annotation to define a method that returns a Spock mock. The method's argument specifies the type of bean to be replaced. Spock's `Mock()` method creates the mock, which is then injected into the test for verification. ```groovy import io.micronaut.test.spock.annotation.MockBean import spock.lang.Specification class MathMockServiceSpec extends Specification { @MockBean(MathService) MathService mathService() { return Mock(MathService) } def "test add with mock"() { when: def result = mathService().add(1, 2) then: 1 * mathService().add(1, 2) >> 3 result == 3 } } ``` -------------------------------- ### Combining @Requires and @Property in a @Refreshable Test Class Source: https://github.com/micronaut-projects/micronaut-test/blob/5.1.x/src/main/docs/guide/junit5/junit5RefreshingInjectedBeansBasedOnRequiresUponPropertiesChanges.adoc Demonstrates how to use `@Refreshable` with `@Requires` and `@Property` annotations to control bean injection based on configuration properties in a JUnit 5 test. ```java package example.refresh; import io.micronaut.context.annotation.Property; import io.micronaut.context.annotation.Requires; import io.micronaut.test.junit5.MicronautTest; import org.junit.jupiter.api.Test; import jakarta.inject.Inject; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; @MicronautTest(transactional = false) @Property(name = "spec.name", value = "PropertyValueRequiresTest") class PropertyValueRequiresTest { @Inject private MyService myService; @Test void testRefreshableBean() { assertNotNull(myService); assertNull(myService.getOptionalBean()); } @Requires(property = "my.feature.enabled", value = "true") @Property(name = "my.feature.enabled", value = "true") @Refreshable static class MyService { @Inject private OptionalBean optionalBean; public OptionalBean getOptionalBean() { return optionalBean; } } @Requires(property = "my.other.feature.enabled", value = "true") @Property(name = "my.other.feature.enabled", value = "true") static class OptionalBean { } } ``` -------------------------------- ### Mocking Collaborator Test Source: https://github.com/micronaut-projects/micronaut-test/blob/5.1.x/src/main/docs/guide/kotest/kotestMockingCollaborators.adoc Tests interaction with a mocked collaborator using `@MockBean` and `HttpClient`. The mock is refreshed for each test iteration. ```kotlin package example.micronaut.kotest.mocking import io.kotest.core.spec.style.StringSpec import io.kotest.matchers.shouldBe import io.micronaut.http.client.HttpClient import io.micronaut.test.extensions.kotest5.MicronautKotest import io.micronaut.test.mock.MockBean @MicronautKotest class MathCollaboratorTest : StringSpec({ "test compute" { val number = 10L val expected = "55" // <1> Like the previous example a Mock is defined using @MockBean // <2> This time we inject an instance of HttpClient to test the controller. val httpClient: HttpClient by v2 // <3> We invoke the controller and retrieve the result val result = httpClient.toBlocking().retrieve("/math/compute/${number}") // <4> The interaction with mock collaborator is verified. result shouldBe expected } }) ``` -------------------------------- ### Importing TestResult in Kotest 6 Source: https://github.com/micronaut-projects/micronaut-test/blob/5.1.x/src/main/docs/guide/breaks.adoc The `TestResult` class has moved from `io.kotest.core.test` to `io.kotest.engine.test` in Kotest 6. ```kotlin import io.kotest.core.test.TestResult ``` ```kotlin import io.kotest.engine.test.TestResult ``` -------------------------------- ### Define a MockBean with Mockito Source: https://github.com/micronaut-projects/micronaut-test/blob/5.1.x/src/main/docs/guide/junit5/usingMockitoMocks.adoc Use `@MockBean` to replace an existing bean with a Mockito mock. The method annotated with `@MockBean` should return the mock instance created by Mockito's `mock()` method. The mock is then injected into the test. ```java import io.micronaut.test.junit5.MathMockService; import jakarta.inject.Inject; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import static org.junit.jupiter.api.Assertions.assertEquals; class MathMockServiceTest { @Inject MathMockService mathService; @Test void testMock() { // given: // <1> The @MockBean annotation is used to indicate the method returns a mock bean. The value to the method is the type being replaced. // <2> Mockito's mock(..) method creates the actual mock MathMockService mock = Mockito.mock(MathMockService.class); // <3> The Mock is injected into the test // <4> Mockito is used to verify the mock is called Mockito.when(mock.add(1, 2)).thenReturn(3); assertEquals(3, mathService.add(1, 2)); Mockito.verify(mock).add(1, 2); } } ``` -------------------------------- ### Enable JUnit Leak Detection with Extension Source: https://github.com/micronaut-projects/micronaut-test/blob/5.1.x/src/main/docs/guide/nettyLeak.adoc To enable leak detection for JUnit Jupiter tests, extend your test class with `JupiterLeakPresenceExtension`. This ensures that any resource leaks are flagged during test execution. ```java import io.netty.buffer.ByteBufAllocator; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @ExtendWith(JupiterLeakPresenceExtension.class) public class LeakyTest { // this test triggers leak detection. @Test void test() { ByteBufAllocator.DEFAULT.buffer(); } } ``` -------------------------------- ### Conditional Test Execution with @Requires Source: https://github.com/micronaut-projects/micronaut-test/blob/5.1.x/src/main/docs/guide/junit5/junit5UsingRequiresOnTests.adoc This test will only execute if the 'my-env' environment is active. Activate the environment by passing the system property 'micronaut.environments'. ```java @MicronautTest @Requires(env = "my-env") class RequiresTest { ... } ``` -------------------------------- ### MathService Interface Definition Source: https://github.com/micronaut-projects/micronaut-test/blob/5.1.x/src/main/docs/guide/junit5/writingAMicronautTestWithJUnit5.adoc Defines the interface for mathematical operations. ```java package example.micronaut.test; public interface MathService { int compute(int value); } ``` -------------------------------- ### Adding Kotest Table Driven Testing Dependency Source: https://github.com/micronaut-projects/micronaut-test/blob/5.1.x/src/main/docs/guide/breaks.adoc For table-driven testing functions like `forAll` and `row`, a new dependency `kotest-assertions-table` is required in Kotest 6. ```kotlin testImplementation("io.kotest:kotest-assertions-table:") ``` ```kotlin import io.kotest.data.blocking.forAll import io.kotest.data.row ``` -------------------------------- ### Combining @Requires and @Property in a @Refreshable Test Class with Kotest Source: https://github.com/micronaut-projects/micronaut-test/blob/5.1.x/src/main/docs/guide/kotest/kotestRefreshingInjectedBeansBasedOnRequiresUponPropertiesChanges.adoc Demonstrates how to configure a test class to refresh beans when property values change. This is useful for verifying that beans with conditional requirements based on properties are re-evaluated correctly. ```kotlin package io.micronaut.test.kotest import io.kotest.core.spec.style.BehaviorSpec import io.micronaut.context.annotation.Property import io.micronaut.context.annotation.Requires import io.micronaut.inject.beans.Refreshable import io.micronaut.test.extensions.kotest.MicronautKotestExtension import io.micronaut.test.extensions.kotest.MicronautKotestExtension.get @Refreshable class PropertyValueRequiresTest : BehaviorSpec({ extension(MicronautKotestExtension) @Property(name = "my.prop", value = "true") @Requires(property = "my.prop") class MyBean @Property(name = "my.prop", value = "false") @Requires(property = "my.prop") class MyBeanDisabled Given("a bean that requires a property") { `When`("the property is set to true") { Then("the bean should be available") { get() } } `When`("the property is set to false") { Then("the bean should not be available") { // This assertion will fail because the bean is not available // get() } } } }) ``` -------------------------------- ### Add Spock Dependencies to Maven POM Source: https://github.com/micronaut-projects/micronaut-test/blob/5.1.x/src/main/docs/guide/spock/settingUpSpock.adoc Add the Micronaut Test Spock dependency to your Maven project's pom.xml file for test scope. ```xml io.micronaut.test micronaut-test-spock test ``` -------------------------------- ### Registering Extensions in Kotest 6 Source: https://github.com/micronaut-projects/micronaut-test/blob/5.1.x/src/main/docs/guide/breaks.adoc In Kotest 6, extensions are registered by overriding the `extensions` property (`val`) instead of the `extensions()` function. ```kotlin override fun extensions() = listOf(MicronautKotest5Extension) ``` ```kotlin override val extensions = listOf(MicronautKotest5Extension) ``` -------------------------------- ### Accessing Test Name in Kotest 6 Source: https://github.com/micronaut-projects/micronaut-test/blob/5.1.x/src/main/docs/guide/breaks.adoc In Kotest 6, the test name is accessed via `testCase.name.name` instead of `testCase.name.testName` from Kotest 5. ```kotlin testCase.name.testName ``` ```kotlin testCase.name.name ``` -------------------------------- ### Renamed JUnit Runner Artifact in Kotest 6 Source: https://github.com/micronaut-projects/micronaut-test/blob/5.1.x/src/main/docs/guide/breaks.adoc The JUnit 5 runner artifact has been renamed to `kotest-runner-junit6-jvm` in Kotest 6 to align with the new major version. ```kotlin testImplementation("io.kotest:kotest-runner-junit5-jvm:") ``` ```kotlin testImplementation("io.kotest:kotest-runner-junit6-jvm:") ``` -------------------------------- ### Using @Property Annotation Source: https://github.com/micronaut-projects/micronaut-test/blob/5.1.x/src/main/docs/guide/junit5/junit5DefiningAdditionalTestSpecificProperties.adoc Use the @Property annotation at the test method level to define individual test-specific properties. This triggers a RefreshEvent to update related @ConfigurationProperties. ```java import io.micronaut.test.junit5.PropertyValueTest; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @ExtendWith(PropertyValueTest.class) public class PropertyValueTest { @Test void testPropertyValue() { // ... test logic using properties defined by @Property } @org.junit.jupiter.api.extension.RegisterExtension static final PropertyValueTest propertyValueTest = new PropertyValueTest(); @Test void testSomething() { // ... } } ```