Kotlin. Micronaut. TestNG test fails in IDEA but pass via gradle - intellij-idea

I have created sample micronaut project with simple testNG test based on this instruction.
The test works perfectly when I run it via gradle from command line, but fails when I try to run it from IDEA.
For successful gradle run in logs I see routing for my controller:
13:40:44.314 [Test worker] DEBUG i.m.web.router.DefaultRouteBuilder - Created Route: GET /hello -> HelloController#String index() (application/json )
which is missing for IDEA run.
QUESTION: What do I need to configure to make the test also pass in IDEA?
sources
src/main/kotlin/example/micronaut/Application.kt:
package example.micronaut
import io.micronaut.runtime.Micronaut
object Application {
#JvmStatic
fun main(args: Array<String>) {
Micronaut.build()
.packages("example.micronaut")
.mainClass(Application.javaClass)
.start()
}
}
src/main/kotlin/example/micronaut/HelloController.kt:
package example.micronaut
import io.micronaut.http.annotation.Controller
import io.micronaut.http.annotation.Get
#Controller("/hello")
class HelloController {
#Get("/")
fun index(): String {
return "Hello World"
}
}
src/test/kotlin/example/micronaut/HelloTest.kt:
package example.micronaut
import io.micronaut.context.ApplicationContext
import io.micronaut.http.client.HttpClient
import io.micronaut.runtime.server.EmbeddedServer
import org.testng.annotations.AfterMethod
import org.testng.annotations.BeforeMethod
import org.testng.annotations.Test
class HelloTest {
lateinit var embeddedServer: EmbeddedServer
lateinit var client: HttpClient
#BeforeMethod
fun init() {
embeddedServer = ApplicationContext.run(EmbeddedServer::class.java)
client = HttpClient.create(embeddedServer.url)
}
#Test
fun check() {
val response: String = client.toBlocking().retrieve("/hello")
assert(response == "Hello World")
}
#AfterMethod
fun cleanup() {
client.close()
embeddedServer.close()
}
}
build.gradle:
buildscript {
repositories {
mavenCentral()
maven { url "https://plugins.gradle.org/m2/" }
}
dependencies {
classpath "com.github.jengelman.gradle.plugins:shadow:2.0.4"
classpath "io.spring.gradle:dependency-management-plugin:1.0.5.RELEASE"
classpath "net.ltgt.gradle:gradle-apt-plugin:0.15"
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.2.31"
}
}
version "0.1"
group "example"
apply plugin:"io.spring.dependency-management"
apply plugin:"com.github.johnrengelman.shadow"
apply plugin:"application"
apply plugin:"java"
apply plugin:"net.ltgt.apt-eclipse"
apply plugin:"net.ltgt.apt-idea"
apply plugin:"kotlin"
apply plugin:"kotlin-kapt"
repositories {
mavenLocal()
mavenCentral()
maven { url "https://jcenter.bintray.com" }
}
dependencyManagement {
imports {
mavenBom 'io.micronaut:bom:1.0.0.M1'
}
}
dependencies {
annotationProcessor "io.micronaut:inject-java"
compile "io.micronaut:http-client"
compile "io.micronaut:http-server-netty"
compile "io.micronaut:inject"
compile "io.micronaut:runtime"
compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.2.31"
compile "org.jetbrains.kotlin:kotlin-reflect:1.2.31"
compileOnly "io.micronaut:inject-java"
kapt "io.micronaut:inject-java"
runtime "ch.qos.logback:logback-classic:1.2.3"
testCompile "io.micronaut:inject-java"
testImplementation("org.testng:testng:6.13.1")
}
shadowJar {
mergeServiceFiles()
}
mainClassName = "example.micronaut.Application"
compileJava.options.compilerArgs += '-parameters'
compileTestJava.options.compilerArgs += '-parameters'
test {
useTestNG()
}
compileKotlin {
kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
kotlinOptions.jvmTarget = "1.8"
}
Solved
fixed by setting gradle as test runner as described in http://mrhaki.blogspot.com/2016/03/gradle-goodness-configure-intellij-idea.html

Currently a build tool is required to build Kotlin + Micronaut applications until IntelliJ brings native support for Kapt. This is explained here https://docs.micronaut.io/latest/guide/index.html#kotlin in the section "Kotlin, Kapt and IntelliJ"

Related

Parameter 0 of constructor in '' required a bean of type '' that could not be found

I am creating a spring boot application, and using doma for O/R mapper.
I could not start application because repositoryimpl can not find dao class , but i can see them in the build/classes . so build is successful but the application fail to start.
How can I fix it?
Package
Build class
dao class
package com.event.app.backend.infrastructure.dao
import com.event.app.backend.infrastructure.table.EventsTableRecord
import org.seasar.doma.Dao
import org.seasar.doma.Select
import org.seasar.doma.Update
import org.seasar.doma.boot.ConfigAutowireable
#ConfigAutowireable
#Dao
interface EventDao {
#Select
fun getEvents():List<EventsTableRecord>
#Select
fun getEventById(eventId:String):EventsTableRecord
#Update(sqlFile = true)
fun updateTicketCnt(eventId:String,bookTicketCnt:Int):Int
#Update(sqlFile = true)
fun subtractTicketCnt(eventId:String,subtractCount:Int):Int
}
impl class
#Repository
class EventRepositoryImpl(
private val eventDao: EventDao,
private val userDao: UserDao,
) : EventRepository {
/**
* get Events
*/
override fun getEvents(): List<Event> {
// return convertToEvent(eventDao.getEvents())
return listOf(Event(
name = "event1",
description = "description1",
date = LocalDate.now(),
availableTickets = 1
))
}
-omit the details-
build.gradle
buildscript{
repositories{
mavenCentral()
}
dependencies {
classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:1.5.10")
classpath("org.springframework.boot:spring-boot-gradle-plugin:2.6.2")
}
}
plugins{
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
}
apply plugin: "java"
apply plugin: "kotlin"
repositories {
mavenCentral()
}
// テンポラリディレクトリのパスを定義する
ext.domaResourcesDir = "${buildDir}/tmp/doma-resources"
// domaが注釈処理で参照するリソースをテンポラリディレクトリに抽出
task extractDomaResources(type: Copy) {
dependsOn processResources
from processResources.destinationDir
include 'doma.compile.config'
include 'META-INF/**/*.sql'
include 'META-INF/**/*.script'
into domaResourcesDir
}
// テンポラリディレクトリ内のリソースをcompileJavaタスクの出力先ディレクトリにコピーする
task copyDomaResources(type: Copy, dependsOn: extractDomaResources) {
dependsOn extractDomaResources
from domaResourcesDir
into compileJava.destinationDir
}
compileJava {
// 上述のタスクに依存させる
dependsOn copyDomaResources
// テンポラリディレクトリをcompileJavaタスクの入力ディレクトリに設定する
inputs.dir domaResourcesDir
options.encoding = 'UTF-8'
}
compileTestJava {
options.encoding = 'UTF-8'
// テストの実行時は注釈処理を無効にする
options.compilerArgs = ['-proc:none']
}
dependencies {
// spring starter web
implementation ("org.springframework.boot:spring-boot-starter-web")
// doma sprig boot starter
implementation ("org.seasar.doma.boot:doma-spring-boot-starter:1.5.0")
// domaの注釈処理を実行することを示す
annotationProcessor 'org.seasar.doma:doma:2.29.0'
// domaへの依存を示す
implementation 'org.seasar.doma:doma:2.29.0'
}
repositories {
mavenCentral()
}
dependencyManagement{
imports{
mavenBom "org.springframework.boot:spring-boot-dependencies:2.6.2"
}
}
tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
kotlinOptions {
jvmTarget = '11'
}
}
added UserDao.kt
package com.event.app.backend.infrastructure.dao
import com.event.app.backend.infrastructure.table.UsersTicketsTableRecord
import org.seasar.doma.Dao
import org.seasar.doma.Insert
import org.seasar.doma.Select
import org.seasar.doma.boot.ConfigAutowireable
#ConfigAutowireable
#Dao
interface UserDao {
#Insert
fun insertUsersTickets(usersTicketsTableRecord: UsersTicketsTableRecord):Result<UsersTicketsTableRecord>
#Select
fun getTicketCntByEventUserId(eventId:String,userId:String):Int
}
You'd need to use kapt instead of annotationProcessor in build.gradle when you use Doma with Kotlin.
The code generated by kapt can be found under build/generated/source/kapt.
The following sample repository may be helpful.
https://github.com/domaframework/kotlin-sample
In the case of Spring Boot, you'd need to define the Dao's in a BeanConfig. I guess it's something similiar in this case.
import org.jdbi.v3.core.Jdbi;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import se.xxx.dao.*;
#Configuration
public class BeanConfig {
#Bean
public SwingPositionDao swingPositionDao(#Qualifier("jdbi.manager") Jdbi jdbi) {
return jdbi.onDemand(SwingPositionDao.class);
}
}

Can I use Spock test in Koltin Multiplatform project? If so how to set in gradle.build.kts?

I try to use Spock test framework in my Kotlin multiplatform project, but with fail, the gradle script:
plugins {
val kotlinVersion = "1.4.30"
kotlin("multiplatform") version kotlinVersion
application
kotlin("plugin.serialization") version kotlinVersion
groovy // for spock
}
repositories {
// ...
maven("https://jitpack.io") // for spock
}
kotlin {
jvm {withJava()}
js {/*...*/}
sourceSets {
val commonMain by getting {
dependencies {/*...*/}
}
val commonTest by getting {
dependencies {
implementation(kotlin("test-common"))
implementation(kotlin("test-annotations-common"))
}
}
val jvmMain by getting {
dependencies {/*...*/}
}
val jvmTest by getting {
dependencies {
dependsOn(commonTest)
implementation(kotlin("test"))
implementation(kotlin("test-junit"))
// implementation(kotlin("test-junit5"))
// for spock
implementation("org.spockframework.spock:spock-core:spock-1.3")
implementation("org.codehaus.groovy:groovy-all:3.0.7")
}
}
val jsMain by getting {
dependencies {/*...*/}
}
}
}
I tried the spock-1.3 and spock-2.0-M4 with groovy-2.5 and Junit5, all failed with dependencies problems, even thought the test can run, it tells: Test events were not received, and more important:
I cannot create groovy source fold for test only.(The directory appreas like normal folder, not source or test folder)
How to configure the dependencies or gradle.build.kts file? Any help is highly appreciated!
I can now make Spock work with existed Ktor project with the code below added to my gradle.build.kts :
plugins {
groovy
}
repositories {
maven("https://jitpack.io")
}
dependencies {
testImplementation("org.codehaus.groovy:groovy-all:2.4.15")
testImplementation("org.spockframework.spock:spock-core:spock-1.3")
}
sourceSets {
main {
withConvention(GroovySourceSet::class) {
groovy {
setSrcDirs(listOf("src"))
}
}
}
test {
withConvention(GroovySourceSet::class) {
groovy {
setSrcDirs(listOf("test"))
}
}
}
}
tasks.test {
useJUnitPlatform()
testLogging {
events("passed", "skipped", "failed")
}
}
However, I cannot figure out the Koltin Multiplatform project with Spock test, I will post the script when I make it.

Could not initialize class org.jetbrains.kotlin.gradle.internal.KotlinSourceSetProviderImplKt by running gradle run via cmd

I have a question about gradle:
I Have the following code in Kotlin (just started to learn it):
#file:JvmName("KtlTest")
fun main(args: Array<String>)
{
println("Hello Kotlin !")
}
and the following build.gradle:
plugins {
id 'org.jetbrains.kotlin.jvm' version '1.2.51'
}
group 'KGroupId'
version '1.0-SNAPSHOT'
ext.kotlin_version = '{{ site.data.releases.latest.version }}'
repositories {
mavenCentral()
}
dependencies {
compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8"
testImplementation 'io.rest-assured:rest-assured:4.3.1'
}
compileKotlin {
kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
kotlinOptions.jvmTarget = "1.8"
}
task runExample(type: JavaExec) {
main = 'KtlTest'
classpath = sourceSets.main.runtimeClasspath
}
If I run this via IntelliJIDEA by clicking green triangle near task - it runs ok.
But, if I run it via other -> runExample in Gradle tab in IntelliJIDEA I got this error:
Also, I got this error if I try to run it via CMD:
Could someone help me figure out what the problem is?

Class 'AuthenticationProviderUserPassword' does not implement abstract member public abstract fun authenticate

I am stuck in user authentication with micronaut application
authenticate function not accepting httpRequest param
I'm getting an error
Class 'AuthenticationProviderUserPassword' is not abstract and does not implement abstract member public abstract fun authenticate(authenticationRequest: AuthenticationRequest<(raw) Any!, (raw) Any!>!): Publisher! defined in io.micronaut.security.authentication.Authenticatio
Service:
package example.micronaut.services
import io.micronaut.http.HttpRequest
import io.micronaut.security.authentication.AuthenticationFailed
import io.micronaut.security.authentication.AuthenticationProvider
import io.micronaut.security.authentication.AuthenticationRequest
import io.micronaut.security.authentication.AuthenticationResponse
import io.micronaut.security.authentication.UserDetails
import io.reactivex.Flowable
import org.reactivestreams.Publisher
import java.util.*
import javax.inject.Singleton
#Singleton // <1>
class AuthenticationProviderUserPassword : AuthenticationProvider { // <2>
override fun authenticate(httpRequest: HttpRequest<*>?, authenticationRequest: AuthenticationRequest<*, *>?): Publisher<AuthenticationResponse> {
if (authenticationRequest != null && authenticationRequest.identity != null && authenticationRequest.secret != null) {
if (authenticationRequest.identity == "sherlock" && authenticationRequest.secret == "password") {
return Flowable.just<AuthenticationResponse>(UserDetails(authenticationRequest.identity as String, ArrayList()))
}
}
return Flowable.just<AuthenticationResponse>(AuthenticationFailed())
}
}
My build.gradle
plugins {
id "org.jetbrains.kotlin.jvm" version "1.3.50"
id "org.jetbrains.kotlin.kapt" version "1.3.50"
id "org.jetbrains.kotlin.plugin.allopen" version "1.3.50"
id "com.github.johnrengelman.shadow" version "5.2.0"
id "application"
}
version "0.1"
group "example.micronaut"
repositories {
mavenCentral()
maven { url "https://jcenter.bintray.com" }
}
configurations {
// for dependencies that are needed for development only
developmentOnly
}
dependencies {
implementation platform("io.micronaut:micronaut-bom:$micronautVersion")
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:${kotlinVersion}"
implementation "org.jetbrains.kotlin:kotlin-reflect:${kotlinVersion}"
implementation "io.micronaut:micronaut-runtime"
implementation "javax.annotation:javax.annotation-api"
implementation "io.micronaut:micronaut-http-server-netty"
implementation "io.micronaut:micronaut-http-client"
implementation "io.micronaut:micronaut-security-session"
kapt platform("io.micronaut:micronaut-bom:$micronautVersion")
kapt "io.micronaut:micronaut-inject-java"
kapt "io.micronaut:micronaut-validation"
kaptTest platform("io.micronaut:micronaut-bom:$micronautVersion")
kaptTest "io.micronaut:micronaut-inject-java"
runtimeOnly "com.fasterxml.jackson.module:jackson-module-kotlin:2.9.8"
runtimeOnly "ch.qos.logback:logback-classic:1.2.3"
testImplementation platform("io.micronaut:micronaut-bom:$micronautVersion")
testImplementation "io.micronaut.test:micronaut-test-kotlintest"
testImplementation "io.mockk:mockk:1.9.3"
testImplementation "io.kotlintest:kotlintest-runner-junit5:3.3.2"
implementation 'junit:junit:4.12'
compile "io.micronaut.configuration:micronaut-hibernate-jpa"
compile "io.micronaut.configuration:micronaut-hibernate-validator"
compileOnly "jakarta.persistence:jakarta.persistence-api:2.2.2"
annotationProcessor "io.micronaut.data:micronaut-data-processor:1.0.2"
runtime "com.h2database:h2"
runtime "io.micronaut.configuration:micronaut-jdbc-tomcat"
}
test.classpath += configurations.developmentOnly
mainClassName = "example.micronaut.Application"
test {
useJUnitPlatform()
}
allOpen {
annotation("io.micronaut.aop.Around")
}
compileKotlin {
kotlinOptions {
jvmTarget = '1.8'
//Will retain parameter names for Java reflection
javaParameters = true
}
}
compileTestKotlin {
kotlinOptions {
jvmTarget = '1.8'
javaParameters = true
}
}
shadowJar {
mergeServiceFiles()
}
tasks.withType(JavaExec) {
classpath += configurations.developmentOnly
jvmArgs('-noverify', '-XX:TieredStopAtLevel=1', '-Dcom.sun.management.jmxremote')
}
The docs you are looking at are compatible with more recent versions of the interface than you are using. You appear to be using the one at https://github.com/micronaut-projects/micronaut-security/blob/78169cb6927d10dcc6ebc2f6ecb96efb26b9585b/security/src/main/java/io/micronaut/security/authentication/AuthenticationProvider.java#L39 which is why your code won't compile. 2.0RC1 looks like https://github.com/micronaut-projects/micronaut-security/blob/d5ecfc200cf27bd92ec7ce7b3760f5c264ec2647/security/src/main/java/io/micronaut/security/authentication/AuthenticationProvider.java#L44.

Kotlin Annotation Processor not working? What am I missing?

Recently I've been trying to make a annotation processor through Kotlin but I can't seem to get it to work. Everything compiles and I don't get any errors but when I check the contents of my jar file I don't see the resource I'm trying to create.
I've tried everything for hours and I'm really stuck so just looking for help :/ I do have one random class annotated to see if it would work but no luck.
The annotation class
#Retention(AnnotationRetention.RUNTIME)
#Target(AnnotationTarget.CLASS)
annotation class TestAnnotation
The processor class
#AutoService(TestAnnotation::class)
class TestAnnotationProcessor : AbstractProcessor() {
override fun process(annotations: MutableSet<out TypeElement>, environment: RoundEnvironment): Boolean {
this.processingEnv.filer.createResource(StandardLocation.CLASS_OUTPUT, "", "test.txt")
return true
}
override fun getSupportedSourceVersion() = SourceVersion.RELEASE_8
override fun getSupportedAnnotationTypes() = setOf(TestAnnotation::class.java.canonicalName)
}
My build.gradle.kts
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
plugins {
java
kotlin("jvm") version "1.3.50"
kotlin("kapt") version "1.3.50"
id("com.github.johnrengelman.shadow") version "5.1.0"
}
group = "com.example.test"
version = "1.0"
repositories {
mavenCentral()
}
dependencies {
implementation(kotlin("stdlib-jdk8"))
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.1")
implementation("com.google.auto.service:auto-service:1.0-rc6")
kapt("com.google.auto.service:auto-service:1.0-rc6")
}
configure<JavaPluginConvention> {
sourceCompatibility = JavaVersion.VERSION_1_8
}
tasks.withType<KotlinCompile> {
kotlinOptions.jvmTarget = "1.8"
}
tasks.withType<ShadowJar> {
dependencies {
exclude(dependency("com.google.auto.service:auto-service:1.0-rc6"))
}
}
In order for your custom annotation processor to work, you will have to use it in your build script dependencies
dependencies {
kapt project(':processor-module') // or what ever your processor's module is named.
//OR
kapt 'gourp:artifact:version' // if your processor is published into a maven repository.
}