Reputation: 195
I am using Micronaut with kotlin, and making the tests with groovy and the Spock framework.
I am now implementing the first unit test for this project.
Whenever I try to run the gradle task "test" or the other one I created "intTest" I always get the error saying that the port is already in use. No matter what port I try to use.
If I start the application with the same port it works. Stop the application, run the test -> doesn't work.
I'm at a loss.
Spec
class UserSpec extends BaseSpec {
void 'test it works'() {
when:
restUtils.getOwnClinician("test")
then:
false
}
}
BaseSpec:
@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)
}
Stack trace:
> 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
Upvotes: 2
Views: 2790
Reputation: 195
First off, I apparently made a mistake by placing the @MicronautTest annotation on a parent class of the test class. This does not seem to be supported by micronaut, and the port binding error went away when I moved the annotation to the test class itself.
After this, when I tried to run the intTest task every request came back with a 401 response. I was only able to fix it by placing the integration tests on the test source set, instead of the intTest source set like I wanted.
It seems that configuring new source sets in micronaut is quite difficult, so I am going to give up on the idea because I don't want to waste any more time on it. I'm still curious if it is possible, so if you have been able to do it, please leave a comment! :)
Upvotes: 1
Reputation: 40078
The error message clearly says the port is already in use, i would recommend to run test on random port using below property in application-test.yml
server:
host: localhost
port: -1
Setting an explicit port may cause tests to fail if multiple servers start simultaneously on the same port. To prevent that, specify a random port in the test environment configuration.
Upvotes: 2