Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Micronaut: Test POST request

In my Micronaut app I have a simple REST controller:

public class Response {
    private String code;

    public Response(String code) {
        this.code = code;
    }
}

@Controller("/api/test")
public class TestController {

    @Post("/")
    public Response index() {
        return new Response("OK");
    }
}

How can I tests this edpoint? I tried using

@MicronautTest
public class TestControllerTest {
    @Inject
    EmbeddedServer server;

    @Inject
    @Client("/")
    HttpClient client;

    @Test
    void testResponse() {
        String response = client.toBlocking()
                .retrieve(HttpRequest.POST("/api/test/"));  // FIXME `HttpRequest.POST` requires body
        assertEquals("{\"code\": \"OK\"}", response);
    }

but HttpRequest.POST requires an additional body argument to be specified. In my case there is no body to be sent. (In the real code it is a request to initialize a new object and thus it has to be POST).

like image 730
Eerik Sven Puudist Avatar asked Jun 16 '26 22:06

Eerik Sven Puudist


1 Answers

Usually, when you implement a POST action, you expect that there is a body sent with the request. In your example, you don't accept any POST body, but you still need to pass anything in the unit test.

You can instantiate the HttpRequest object in the following way:

HttpRequest.POST("/api/test/", "");

You can't pass null, it has to be some non-null value (like an empty string.)

like image 151
Szymon Stepniak Avatar answered Jun 19 '26 23:06

Szymon Stepniak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!