如何配置Micronaut在执行单元测试时禁止启动嵌入式服务器?
test Tasks Absolutely! You can totally configure Micronaut to skip spinning up the embedded server when running your Gradle test task—this is super common for CI environments where you don’t have (or don’t need) a database available for unit tests. Here are a few straightforward ways to make this work:
1. Disable Server for Individual Tests with @MicronautTest
If your tests use the @MicronautTest annotation, simply add the server = false attribute to disable the embedded server for that specific test class:
import io.micronaut.test.extensions.junit5.annotation.MicronautTest; @MicronautTest(server = false) public class UserServiceUnitTest { // Your unit test logic here }
This will initialize Micronaut's dependency injection container so you can inject beans, but it won't start the HTTP server—meaning no attempts to connect to a database (unless your test explicitly requires it, in which case you might want to use an in-memory database or test containers).
2. Globally Disable Server for All Tests via Gradle
If you want to apply this setting to all tests without modifying each class, add a system property to your build.gradle (or build.gradle.kts) file:
Groovy DSL (build.gradle)
test { systemProperty 'micronaut.server.enabled', 'false' }
Kotlin DSL (build.gradle.kts)
tasks.test { systemProperty("micronaut.server.enabled", "false") }
This tells Micronaut to skip starting the server during the entire test task execution, which is perfect for CI pipelines where you only need to run lightweight unit tests.
3. Split Tests into Unit and Integration Test Suites
For a more structured approach, separate your unit tests (no server needed) from integration tests (server required) using Gradle's source sets. This lets you run only the tests you need in each environment:
Step 1: Configure Integration Test Source Set (Groovy DSL)
sourceSets { integrationTest { java.srcDir file('src/integration-test/java') resources.srcDir file('src/integration-test/resources') compileClasspath += sourceSets.main.output + configurations.testRuntimeClasspath runtimeClasspath += output + compileClasspath } } task integrationTest(type: Test) { description = 'Runs integration tests that require a running server' group = 'Verification' testClassesDirs = sourceSets.integrationTest.output.classesDirs classpath = sourceSets.integrationTest.runtimeClasspath shouldRunAfter test } check.dependsOn integrationTest
Step 2: Annotate Tests Appropriately
- Use
@MicronautTest(server = false)for unit tests insrc/test/java - Use regular
@MicronautTest(withoutserver=false) for integration tests insrc/integration-test/java
In CI, you can run just the unit tests with ./gradlew test, or run integration tests separately (with a database available) using ./gradlew integrationTest.
内容的提问来源于stack exchange,提问作者Lucas Andrade

