Micronaut gradle 测试不工作,说每个端口都已经绑定

如何解决Micronaut gradle 测试不工作,说每个端口都已经绑定

我将 Micronaut 与 kotlin 结合使用,并使用 groovy 和 Spock 框架进行测试。

我现在正在为这个项目实施第一个单元测试。

每当我尝试运行 gradle 任务“test”或我创建的另一个任务“intTest”时,我总是收到错误消息,指出端口已在使用中。无论我尝试使用什么端口。

如果我使用相同的端口启动应用程序,它就可以工作。停止应用程序,运行测试 -> 不起作用。

我不知所措。

规格

class UserSpec extends BaseSpec {

    void 'test it works'() {
        when:
        restUtils.getOwnClinician("test")

        then:
        false
    }
}

基本规格:

@MicronautTest(propertySources="classpath:application-test.yaml")
abstract class BaseSpec extends Specification {

    @Inject
    EmbeddedServer embeddedServer

    RestUtils restUtils = new RestUtils("http://localhost:" + embeddedServer.port)
}

application-test.yaml:

micronaut:
  server:
    host: localhost
    port: 8081

build.gradle:

// Import gradle plugins
plugins {
    id("org.jetbrains.kotlin.jvm") version "1.4.10"
    id("org.jetbrains.kotlin.kapt") version "1.4.10"
    id("org.jetbrains.kotlin.plugin.allopen") version "1.4.10"
    id("groovy")
    id("com.github.johnrengelman.shadow") version "6.1.0"
    id("io.micronaut.application") version "1.3.4"
    id("org.jetbrains.kotlin.plugin.noarg") version "1.5.0-M1"
}

// Define dependencies versions
version = "0.1"
group = "com."

val kotlinVersion=project.properties.get("kotlinVersion")
val springSecurityCryptoVersion=project.properties.get("springSecurityCryptoVersion")

// Dependency repository configuration
repositories {
    mavenCentral()
}

// Micronaut plugin configurations
micronaut {
    runtime("netty")
    testRuntime("spock2")
    processing {
        incremental(true)
        annotations("com.*")
    }
}

// Define depenencies
val intTestImplementation by configurations.creating {
    extendsFrom(configurations.testImplementation.get())
}

val intTestKapt by configurations.creating {
    extendsFrom(configurations.kaptTest.get())
}

dependencies {
    implementation("io.micronaut:micronaut-validation")
    implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8:${kotlinVersion}")
    implementation("org.jetbrains.kotlin:kotlin-reflect:${kotlinVersion}")
    implementation("io.micronaut.kotlin:micronaut-kotlin-runtime")
    implementation("io.micronaut:micronaut-runtime")
    implementation("javax.annotation:javax.annotation-api")
    implementation("io.micronaut:micronaut-http-client")
    implementation("io.micronaut:micronaut-http")
    implementation("io.micronaut.sql:micronaut-jdbc-hikari")
    implementation("io.micronaut.sql:micronaut-hibernate-jpa")
    implementation("io.micronaut.data:micronaut-data-hibernate-jpa")
    implementation("io.micronaut.liquibase:micronaut-liquibase")
    implementation("org.slf4j:jul-to-slf4j:1.7.30")
    implementation("io.micronaut.beanvalidation:micronaut-hibernate-validator")
    implementation("io.swagger.core.v3:swagger-annotations")
    implementation("io.micronaut.security:micronaut-security-jwt")
    implementation("org.springframework.security:spring-security-crypto:${springSecurityCryptoVersion}")
    implementation("commons-logging:commons-logging:1.2")

    kapt("io.micronaut.security:micronaut-security-annotations")
    kapt("io.micronaut.data:micronaut-data-processor")
    kapt("io.micronaut.openapi:micronaut-openapi")
    kapt("io.micronaut:micronaut-inject-java")
    runtimeOnly("ch.qos.logback:logback-classic")
    runtimeOnly("com.fasterxml.jackson.module:jackson-module-kotlin")
    runtimeOnly("mysql:mysql-connector-java:8.0.22")

    intTestImplementation("io.micronaut.test:micronaut-test-core:2.3.2")
    intTestImplementation("io.micronaut.test:micronaut-test-spock:2.3.2")
    intTestImplementation("org.codehaus.groovy.modules.http-builder:http-builder:0.7.1")
    intTestImplementation("org.slf4j:jul-to-slf4j:1.7.30")
    intTestImplementation("mysql:mysql-connector-java:8.0.22")
    intTestImplementation("io.micronaut:micronaut-inject-groovy")
    intTestImplementation("org.codehaus.groovy:groovy-all:3.0.7")
    intTestKapt("io.micronaut:micronaut-inject-groovy")

    testImplementation("io.micronaut.test:micronaut-test-core:2.3.2")
    testImplementation("io.micronaut.test:micronaut-test-spock:2.3.2")
    testImplementation("org.codehaus.groovy.modules.http-builder:http-builder:0.7.1")
    testImplementation("org.slf4j:jul-to-slf4j:1.7.30")
    testImplementation("mysql:mysql-connector-java:8.0.22")
    testImplementation("io.micronaut:micronaut-inject-groovy")
    testImplementation("org.codehaus.groovy:groovy-all:3.0.7")
    kaptTest("io.micronaut:micronaut-inject-groovy")
}

// Configure kapt plugin
kapt {
    arguments {
        arg("micronaut.openapi.views.spec","redoc.enabled=true,rapidoc.enabled=true,swagger-ui.enabled=true,swagger-ui.theme=flattop")
        arg("micronaut.processing.incremental",true)
        arg("micronaut.processing.annotations","com.*")
    }
}

// Configure annotations for which constructors with no arguments will be generated
noArg {
    annotation("javax.persistence.Entity")
    annotation("javax.persistence.MappedSuperclass")
}

// Application configs
application {
    mainClass.set("com.ApplicationKt")
}

java {
    sourceCompatibility = JavaVersion.toVersion("14")
}

tasks {
    compileKotlin {
        kotlinOptions {
            jvmTarget = "14"
        }
    }
    compileTestKotlin {
        kotlinOptions {
            jvmTarget = "14"
        }
    }
}

// Integration tests
sourceSets.create("intTest") {
    withConvention(GroovySourceSet::class) {
        groovy.srcDir("src/intTest/groovy")
    }
    resources.srcDir("src/intTest/resources")
}

tasks.register<Jar>("intTestJar") {
    from(sourceSets["intTest"].output)
}

tasks.register<Javadoc>("intTestJavadoc") {
    source(sourceSets["intTest"].allJava)
}

val intTest by tasks.registering(Test::class) {
    testClassesDirs = sourceSets["intTest"].output.classesDirs
    classpath = sourceSets["intTest"].runtimeClasspath
    group = "verification"

    outputs.upToDateWhen { false }
    useJUnitPlatform()
    exclude("**/BaseIT*")
    exclude("**/TestUtils*")
    mustRunAfter(tasks.test)
}

tasks.check.configure {
    dependsOn(intTest)
}

堆栈跟踪:

> Task :kaptGenerateStubsIntTestKotlin NO-SOURCE
> Task :kaptIntTestKotlin
> Task :compileIntTestKotlin NO-SOURCE
> Task :compileIntTestJava NO-SOURCE
> Task :compileIntTestGroovy
> Task :processIntTestResources
> Task :intTestClasses
> Task :intTest
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.

Unable to start Micronaut server on port: 8081
io.micronaut.http.server.exceptions.ServerStartupException: Unable to start Micronaut server on port: 8081
    at io.micronaut.http.server.netty.NettyHttpServer.bindServerToHost(NettyHttpServer.java:496)
    at io.micronaut.http.server.netty.NettyHttpServer.start(NettyHttpServer.java:314)
    at io.micronaut.http.server.netty.NettyHttpServer.start(NettyHttpServer.java:112)
    at io.micronaut.test.extensions.AbstractMicronautExtension.beforeClass(AbstractMicronautExtension.java:239)
    at io.micronaut.test.extensions.spock.MicronautSpockExtension.lambda$visitSpecAnnotation$3(MicronautSpockExtension.java:97)
    at org.spockframework.runtime.extension.MethodInvocation.proceed(MethodInvocation.java:101)
    at org.spockframework.runtime.model.MethodInfo.invoke(MethodInfo.java:136)
    at org.spockframework.runtime.extension.MethodInvocation.proceed(MethodInvocation.java:102)
    at io.micronaut.test.extensions.spock.MicronautSpockExtension.lambda$visitSpecAnnotation$3(MicronautSpockExtension.java:117)
    at org.spockframework.runtime.extension.MethodInvocation.proceed(MethodInvocation.java:101)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:136)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
    at org.spockframework.runtime.model.MethodInfo.invoke(MethodInfo.java:136)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:143)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:108)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:54)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:96)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:75)
    at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.processAllTestClasses(JUnitPlatformTestClassProcessor.java:99)
    at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.access$000(JUnitPlatformTestClassProcessor.java:79)
    at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor.stop(JUnitPlatformTestClassProcessor.java:75)
    at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.stop(SuiteTestClassProcessor.java:61)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:33)
    at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:94)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.stop(TestWorker.java:133)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:182)
    at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:164)
    at org.gradle.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:414)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:48)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:56)
    at java.base/java.lang.Thread.run(Thread.java:832)
Caused by: java.net.BindException: Address already in use
    at java.base/sun.nio.ch.Net.bind(Net.java:550)
    at java.base/sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:249)
    at io.netty.channel.socket.nio.NioServerSocketChannel.doBind(NioServerSocketChannel.java:134)
    at io.netty.channel.AbstractChannel$AbstractUnsafe.bind(AbstractChannel.java:550)
    at io.netty.channel.DefaultChannelPipeline$HeadContext.bind(DefaultChannelPipeline.java:1334)
    at io.netty.channel.AbstractChannelHandlerContext.invokeBind(AbstractChannelHandlerContext.java:506)
    at io.netty.channel.AbstractChannelHandlerContext.bind(AbstractChannelHandlerContext.java:491)
    at io.netty.channel.DefaultChannelPipeline.bind(DefaultChannelPipeline.java:973)
    at io.netty.channel.AbstractChannel.bind(AbstractChannel.java:248)
    at io.netty.bootstrap.AbstractBootstrap$2.run(AbstractBootstrap.java:356)
    at io.netty.util.concurrent.AbstractEventExecutor.safeExecute(AbstractEventExecutor.java:164)
    at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:472)
    at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:500)
    at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:989)
    at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)
    at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
    ... 1 more

UserSpec > initializationError FAILED
    io.micronaut.http.server.exceptions.ServerStartupException at NettyHttpServer.java:496
        Caused by: java.net.BindException at Net.java:550
1 test completed,1 failed
> Task :intTest FAILED
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':intTest'.
> There were failing tests. See the report at: file:///Users/lucas/Documents/workspace/platform/build/reports/tests/intTest/index.html
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
Deprecated Gradle features were used in this build,making it incompatible with Gradle 7.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/6.8/userguide/command_line_interface.html#sec:command_line_warnings
BUILD FAILED in 12s
4 actionable tasks: 4 executed

解决方法

错误消息清楚地表明端口已被使用,我建议使用 application-test.yml 中的以下属性在随机端口上运行测试

server:
  host: localhost
  port: -1

Random Port Micronuat

如果多个服务器同时在同一端口上启动,则设置显式端口可能会导致测试失败。为防止出现这种情况,请在测试环境配置中指定一个随机端口。

,

首先,我显然犯了一个错误,将@MicronautTest 注释放在测试类的父类上。 micronaut好像不支持这个,当我把注解移到测试类本身时,端口绑定错误就消失了。

此后,当我尝试运行 intTest 任务时,每个请求都返回 401 响应。我只能通过将集成测试放在测试源集上来修复它,而不是我想要的 intTest 源集。

看来在 micronaut 中配置新的源集相当困难,所以我打算放弃这个想法,因为我不想在上面浪费更多时间。我仍然很好奇是否可能,所以如果你能够做到,请发表评论! :)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res