[JAVA] Introduction to Micronaut 2 ~ Unit test ~

Overview

Introduction to Micronaut 1 ~ Introduction ~ continued Perform a unit test by slightly extending the HelloController created last time. Use the Micronaut extension module Micronaut Test.

What is Micronaut Test?

Test framework for Micronaut

You can test with either. This time I will test using JUnit 5.

Modification / addition of implementation class

Controller fix

Add a test method to HelloController.

HelloController.java


import io.micronaut.http.MediaType;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;
import my.app.service.HelloService;

@Controller("/hello")
public class HelloController {
    HelloService helloService;

    HelloController(HelloService helloService) {
        this.helloService = helloService;
    }

    @Get(produces = MediaType.TEXT_PLAIN)
    public String index() {
        return "hello world!!";
    }

    //Added for testing with multiple parameters
    @Get(uri = "/{path}",processes = MediaType.TEXT_PLAIN)
    public String index(String path) {
        return path;
    }

    //Service class processing Added for Mock confirmation
    @Get(uri = "/compute/{number}",processes = MediaType.TEXT_PLAIN)
    public String compute(Integer number) {
        //Set the compute method to Mock during testing.
        return String.valueOf(helloService.compute(number));
    }
}
Add service class

HelloService


public interface HelloService {
    public Integer compute(Integer num);
}

HelloServiceImpl


import javax.inject.Singleton;

@Singleton
public class HelloServiceImpl implements HelloService {
    @Override
    public Integer compute(Integer num) {
        return num * 4;
    }
}

Unit test

Add dependent libraries

build.gradle


dependencies {
・ ・ ・
    testAnnotationProcessor "io.micronaut:micronaut-inject-java"
    testCompile "io.micronaut.test:micronaut-test-junit5"
    testCompile "org.junit.jupiter:junit-jupiter-params"
    testCompile "org.mockito:mockito-core:2.24.5"
    testRuntime "org.junit.jupiter:junit-jupiter-engine"
}
Add unit test

HelloControllerTest.java


import io.micronaut.http.HttpRequest;
import io.micronaut.http.client.RxHttpClient;
import io.micronaut.http.client.annotation.Client;
import io.micronaut.test.annotation.MicronautTest;
import io.micronaut.test.annotation.MockBean;
import my.app.service.HelloService;
import my.app.service.HelloServiceImpl;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;

import javax.inject.Inject;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.*;

@MicronautTest
public class HelloControllerTest {
    //Test HelloController with RxHttpClient
    @Inject
    @Client("/")
    RxHttpClient client;

    @Inject
    HelloService helloService;

    @Test
    void testHelloIndex() {
        final String result = client.toBlocking().retrieve(HttpRequest.GET("/hello"), String.class);
        assertEquals(
                "hello world!!",
                result
        );
    }

    @ParameterizedTest
    //You can pass multiple parameters and test multiple times with the same source
    @ValueSource(strings = { "racecar", "radar" })
    void testHelloIndexPath(String path) {
        final String result = client.toBlocking().retrieve(HttpRequest.GET("/hello/" + path), String.class);
        assertEquals(
                path,
                result
        );
    }

    @ParameterizedTest
    @CsvSource({"2,4", "3,9"})
    void testComputeNumToSquare(Integer num, Integer square) {

        //Set the behavior of Mock
        when(helloService.compute(num))
                .then(invocation -> Long.valueOf(Math.round(Math.pow(num, 2))).intValue());

        //Call the controller to get the result
        final Integer result = client.toBlocking().retrieve(HttpRequest.GET("/hello/compute/" + num), Integer.class);

        assertEquals(
                square,
                result
        );
        verify(helloService).compute(num);
    }

    //Mock definition using MockBean
    @MockBean(HelloServiceImpl.class)
    HelloService mathService() {
        return mock(HelloService.class);
    }
}

Impressions

Since it is a unit test using JUnit, the introduction barrier seems to be low. Since Micronaut started up quickly, the test was light and good.

reference

https://micronaut-projects.github.io/micronaut-test/latest/guide/index.html

Recommended Posts

Introduction to Micronaut 2 ~ Unit test ~
Introduction to Micronaut 1 ~ Introduction ~
Introduction to RSpec 1. Test, RSpec
How to unit test Spring AOP
Introduction to Ruby 2
Java Artery-Easy to use unit test library
Introduction to SWING
Introduction to web3j
[Java] Introduction to Java
Introduction to migration
Introduction to java
Introduction to Doma
Model unit test code to check uniqueness constraints
Introduction to Ratpack (8)-Session
Introduction to bit operation
Introduction to Ratpack (6) --Promise
Introduction to Ratpack (9) --Thymeleaf
Introduction to PlayFramework 2.7 ① Overview
Introduction to Android Layout
Java Unit Test Library-Artery-Sample
Introduction to design patterns (introduction)
Introduction to Practical Programming
Introduction to javadoc command
Introduction to jar command
Introduction to Ratpack (2)-Architecture
Introduction to lambda expression
Unit test with Junit.
Introduction to java command
Introduction to RSpec 2. RSpec setup
Introduction to Keycloak development
Introduction to javac command
How to write a unit test for Spring Boot 2
How to unit test with JVM with source using RxAndroid
Introduction to RSpec 4. Create test data with Factory Bot
How to dynamically write iterative test cases using test / unit (Test :: Unit)
Introduction to Design Patterns (Builder)
Introduction to RSpec 5. Controller specs
Introduction to RSpec 6. System specifications
Introduction to Android application development
Introduction to RSpec 3. Model specs
Introduction to Ratpack (5) --Json & Registry
Introduction to Metabase ~ Environment Construction ~
Introduction to Ratpack (7) --Guice & Spring
(Dot installation) Introduction to Java8_Impression
[IntelliJ IDEA] Perform Unit Test
Introduction to Design Patterns (Composite)
Introduction to JUnit (study memo)
Introduction to Spring Boot ① ~ DI ~
Unit test architecture using ArchUnit
Introduction to design patterns (Flyweight)
[Java] Introduction to lambda expressions
Introduction to Spring Boot ② ~ AOP ~
Introduction to Apache Beam (2) ~ ParDo ~
[Ruby] Introduction to Ruby Error statement
Introduction to EHRbase 2-REST API
Introduction to design patterns Prototype
Implementation of unit test code
GitHub Actions Introduction to self-made actions
[Rails] Integration test using Capybara (from introduction to simple test execution)
[Java] Introduction to Stream API
Introduction to Design Patterns (Iterator)