Showing posts with label kotlin. Show all posts
Showing posts with label kotlin. Show all posts

Sunday, October 28, 2018

Slimming down a Spring Boot app for testing

One of my favorite things about Spring Boot is the ability to launch an application in embedded mode and do some pseudo-integration-testing (that is, it's integration testing because I'm able to call the embedded app over the loopback network, as if the test were running on a different machine).   Of course you can launch your 'real' application that lives in your 'main' source folder, and you can enable / disable parts of the application with Spring profiles.

But what if you want to create a specialized Spring Boot app, just for testing?   Well, you can!

For example, in src/test/org/example/test/app/TestServer.kt we can make an app class (btw, this is Kotlin, just so you know):

package org.example.test.app

...imports blah...

@SpringBootApplication()
@Import(SomeConfig::class)
class TestGraphQLClientApp {
    /**
     * Defines the main resolvers: Query and Mutation.
     */
    @Bean
    fun resolvers(query: GraphQLQueryResolver) = listOf(query)

}

  • This is a GraphQL server, and I'm going to test a simple GraphQL client with it.   There are more components behind the scenes.
  • I'm putting it in the app sub-package to avoid loading any component in the main app or anywhere else unintentionally.    Remember that a Spring Boot app class implies a 'component scan' of the package it lives in, and all sub-packages!
  • SomeConfig is imported, and this brings in whatever components from the main code or elsewhere.
  • Specialized test components can be defined in packages or sub-packages.
We can make a test like this:

package org.example.test

... imports blah ...

@RunWith(SpringJUnit4ClassRunner::class)
@SpringBootTest(classes = [TestGraphQLClientApp::class, HttpClientConfiguration::class],
        webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class GraphQLClientTest {
    companion object : KLogging()

    @LocalServerPort
    private val port: Int = 0

    @Autowired
    private lateinit var factory: RestTemplateFactory

    // These have to be 'by lazy' because Spring will inject the fields they rely on after init.

    private val template by lazy { factory.createRestTemplate() }

    private val baseUrl by lazy { "http://localhost:$port/graphql" }

    private val client by lazy { GraphQLClient(baseUrl, template) }

    @Test
    fun basicClientTest() {
        client.query("query { foo }").also { value ->
            logger.info { prettyPrint(value) }
            assertEquals("foo", assertHasField(value, "data", "foo").asText())
        }
        client.query("query { getThing(id: \"12345-ABC\") { one two } }").also {
            logger.info { prettyPrint(it) }
        }
    }
}
  • Note that the default 'properties' will be loaded from application.properties or application.yml.  If we want to override this, we should probably make a profile and use it from the test.
So what's the problem?   The problem is that, in this particular context I have JPA and a few other Spring Boot 'starter' dependencies.   So, when the test class starts the Spring Boot app, it launches:
  1. A JDBC Data Source
  2. Liquibase (my preferred data migration tool)
  3. JPA and Hibernate
Those are all great tools, and it's super convenient to have all these 'auto starters' but they are not needed in this particular test.   How to turn them off and "slim" down my application?   There are two approaches:
  1. Create a profile, and disable some things in that profile - This works for the autostart modules that support it, but not all of them do.
  2. Use 'exclude' in SpringBootApplication to disable the autostart modules.
Using exclude is easy, and since it prevents Spring from loading the autostart modules in the first place, it can reduce startup time.   So for a simple web app, we can disable all the database modules:

@SpringBootApplication(exclude = [
    LiquibaseAutoConfiguration::class,
    DataSourceAutoConfiguration::class,
    DataSourceTransactionManagerAutoConfiguration::class,
    HibernateJpaAutoConfiguration::class])

That's all we need to do!   Now the test app starts up in about 9 seconds.

See also:



Saturday, June 24, 2017

Kotlin: Getting Started - Part 1

I've been using Kotlin for a month or so now, and here are some of the smaller things that I found very useful.

Some Basic Patterns

Here are some basic patterns that you probably (hopefully) use in Java, and how to do them with Kotlin.

Builder/Constructor

In Java you may have classes with many overloaded constructors, or with constructors that have lots of nullable parameters.   I think we can all agree that this is just all around tedious for both the producer of the class and the consumer / caller.   You might decide to make a builder, which allows you to have a single constructor, and have immutable fields in your target class.   While this can make things a bit easier for the consumer/caller,  it's still a lot of boilerplate code.

 Kotlin provides with two features that can help with this in some cases:
  1. Optional parameters with default values
  2. Named parameters
Of course, you can still make a builder if you want.  Also, you can define secondary constructors.

Caveat for Java integration: These features are not available for Java code calling Kotlin, so don't expect this to magically improve Java.

Memoize

It's really easy to create an 'initialize once' field in Kotlin: just use: as lazy { ... }


You can chain these together, due to the fact that the 'as lazy' properties act just like normal properties.



Integrating with Existing Java Code

If you're considering Kotlin, but you have a bunch of existing Java code you might be concerned about using Kotlin into your code base.   Fortunately, Kotlin support is really easy to add to your build, and it's very easy to interoperate between Kotlin and Java.

Adding Kotlin Support - Gradle

To add Kotlin compilation support to an existing Gradle build.


  1. Put the Kotlin plugins in the buildscript class path:

    buildscript {
        ext {
            kotlinVersion = '1.1.2-4'
        }
        repositories {
            jcenter()
            maven { url "https://plugins.gradle.org/m2/" }
        }
    
        dependencies {    // Gradle Plugin classpath.
            classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:${kotlinVersion}")
            classpath("org.jetbrains.kotlin:kotlin-allopen:${kotlinVersion}")
            classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:${kotlinVersion}"
        }
    }
    

    NOTE: I'm avoiding the newer Gradle plugin configuration syntax because it does not support string interpolation. You have to repeat the kotlinVersion information over and over.
  2. Enable the Kotlin plugins:
    
    
        apply plugin: 'kotlin'
        apply plugin: 'kotlin-spring'
    
  3. 
    
  4. Set the target JVM (optional, but I prefer to do this):

        compileKotlin {
            kotlinOptions.jvmTarget = "1.8"
        }
    
        compileTestKotlin {
            kotlinOptions.jvmTarget = "1.8"
        }
    

  5. Add the Kotlin runtime library dependencies:

        dependencies { 
            // Kotlin/JVM libraries
            compile("org.jetbrains.kotlin:kotlin-stdlib:${kotlinVersion}")
            compile("org.jetbrains.kotlin:kotlin-stdlib-jre8:${kotlinVersion}")
            compile("org.jetbrains.kotlin:kotlin-reflect:${kotlinVersion}")
            // Kotlin SLF4J utility
            compile 'io.github.microutils:kotlin-logging:1.4.4'
        }
    

Calling Kotlin Functions from Java


Java will see Kotlin functions as static methods in a class named like this: <package><KotlinFileName>Kt.   Basically, just the class name you might expect, plus 'Kt' on the end.