Testing Functions

Functions can also be run as part of the Micronaut application context for ease of testing. Similarly to the example above, this approach requires the function-web and an HTTP server dependency on the classpath for tests. For example, in build.gradle:

  1. testImplementation("io.micronaut:micronaut-http-server-netty")
  1. <dependency>
  2. <groupId>io.micronaut</groupId>
  3. <artifactId>micronaut-http-server-netty</artifactId>
  4. <scope>test</scope>
  5. </dependency>
  1. testImplementation("io.micronaut:micronaut-function-web")
  1. <dependency>
  2. <groupId>io.micronaut</groupId>
  3. <artifactId>micronaut-function-web</artifactId>
  4. <scope>test</scope>
  5. </dependency>
In order to run the function as a web application, you will need an HTTP server, such as the http-server-netty dependency

Create a @FunctionClient interface as shown below:

MathClient.groovy

  1. import io.micronaut.function.client.FunctionClient
  2. import javax.inject.Named
  3. @FunctionClient
  4. static interface MathClient {
  5. Long max() (1)
  6. @Named("round")
  7. int rnd(float value)
  8. }
For further information on the use of @FunctionClient, please see Calling Functions.

Now you can start up the Micronaut application and access your function via the client interface in your test.

  1. void "test invoking a local function"() {
  2. given:
  3. EmbeddedServer server = ApplicationContext.run(EmbeddedServer)
  4. MathClient mathClient = server.getApplicationContext().getBean(MathClient)
  5. expect:
  6. mathClient.max() == Integer.MAX_VALUE.toLong()
  7. mathClient.rnd(1.6) == 2
  8. mathClient.sum(new Sum(a:5,b:10)) == 15
  9. }