Creating your first Micronaut Kotlin app

Learn how to create a Micronaut app with Kotlin with a controller and a functional test.

Authors: Sergio del Amo

Micronaut Version: 1.0.0.RC2

1 Getting Started

In this guide we are going to create a Micronaut app written in Kotlin.

1.1 What you will need

To complete this guide, you will need the following:

  • Some time on your hands

  • A decent text editor or IDE

  • JDK 1.8 or greater installed with JAVA_HOME configured appropriately

1.2 Solution

We recommend you to follow the instructions in the next sections and create the app step by step. However, you can go right to the completed example.

or

Then, cd into the complete folder which you will find in the root project of the downloaded/cloned project.

2 Writing the App

Create a Kotlin Micronaut app using the Micronaut Command Line Interface.

mn create-app example.micronaut.complete --features=kotlin

The previous command createas a micronaut app with the default package example.micronaut in a folder named complete.

Due to the --features kotlin flag, it generates a Kotlin Micronaut app and it uses Gradle build system. However, you could use other build tool such as Maven or other programming languages such as Java or Groovy.

If you are using Java or Kotlin and IntelliJ IDEA make sure you have enabled annotation processing.

annotationprocessorsintellij

Kotlin, Kapt and IntelliJ

As of this writing IntelliJ’s built-in compiler does not directly support Kapt and annotation processing. You must instead configure Intellij to run Gradle (or Maven) compilation as a build step before running your tests or application class.

First edit the run configuration for tests or for the application and select "Run Gradle task" as a build step:

Intellij Settings

Then add the classes task as task to execute for the application or for tests the testClasses task:

Intellij Settings

Now whenever you run tests or the application Micronaut classes will be generated at compilation time.

Read Micronaut Kotlin section to learn more.

Alternatively, you can delegate IntelliJ build/run actions to gradle completely:

delegatetogradle

3 Controller

In order to create a microservice that responds to "Hello World" you first need a controller.

Create a Controller:

src/main/kotlin/example/micronaut/HelloController.kt
package example.micronaut

import io.micronaut.http.MediaType
import io.micronaut.http.annotation.Controller
import io.micronaut.http.annotation.Get
import io.micronaut.http.annotation.Produces

@Controller("/hello") (1)
class HelloController {

    @Get("/")  (2)
    @Produces(MediaType.TEXT_PLAIN) (3)
    fun index(): String {
        return "Hello World"  (4)
    }
}
1 The class is defined as a controller with the @Controller annotation mapped to the path /hello
2 The @Get annotation is used to map the index method to all requests that use an HTTP GET
3 By default a Micronaut’s response uses application/json as Content-Type. We are returning a String not a JSON object. Because of that, we set it to text/plain.
4 A String "Hello World" is returned as the result

4 Test

In this tutorial, we use Spek 2 to test the microservices:

gradle.properties
kotlinVersion=1.2.61
spekVersion=2.0.0-alpha.1
micronautVersion=1.0.0.RC2
bookcatalogue/build.gradle
repositories {
...
..
    maven { url "https://dl.bintray.com/spekframework/spek-dev" }
}
dependencies {
    ...
    ..
    .
    testImplementation "org.jetbrains.kotlin:kotlin-test:$kotlinVersion"
    testImplementation "org.spekframework.spek2:spek-dsl-jvm:$spekVersion"
    testRuntimeOnly "org.spekframework.spek2:spek-runner-junit5:$spekVersion"
}

test {
    useJUnitPlatform {
        includeEngines 'spek2'
    }
}

Create a test which verifies that when you do a GET request to /hello you get Hello World as a response:

src/test/kotlin/example/micronaut/HelloControllerSpec.kt
package example.micronaut

import io.micronaut.context.ApplicationContext
import io.micronaut.http.client.HttpClient
import io.micronaut.runtime.server.EmbeddedServer
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
import kotlin.test.assertEquals

object BooksControllerSpec: Spek({
    describe("BookController Suite") {
        var embeddedServer : EmbeddedServer = ApplicationContext.run(EmbeddedServer::class.java) (1)
        var client : HttpClient = HttpClient.create(embeddedServer.url) (2)

        it("test /hello responds Hello World") {
            var rsp : String = client.toBlocking().retrieve("/hello")
            assertEquals(rsp, "Hello World")
        }

        afterGroup {
            client.close()
            embeddedServer.close()
        }
    }
})
1 To run the application from a unit test you can use the EmbeddedServer interface
2 Register an HttpClient bean in the application context and point it to the embedded server URL. The EmbeddedServer interface provides the URL of the server under test which runs on a random port.

5 Testing the Application

To run the tests:

$ ./gradlew test
$ open build/reports/tests/test/index.html

6 Running the Application

Before running the Application, adapt the in build.gradle the

build.gradle
...
mainClassName = "example.micronaut.Application"
...

To run the application use the ./gradlew run command which will start the application on a random port.