Lesson 9: GraalVM with Quarkus – JUnit and RestAssured

Lesson 9: GraalVM with Quarkus – JUnit and RestAssured
This lesson covers testing techniques in GraalVM-optimized Quarkus applications, focusing on JUnit for unit testing and RestAssured for API testing.


JUnit Integration: 2 Key Points

  1. Seamless Unit Testing
    Quarkus supports JUnit natively, enabling developers to write efficient unit tests for applications. GraalVM compatibility ensures that tests run quickly, even when executed in native image builds, helping maintain rapid feedback cycles during development.

  2. Testing Native Images
    Quarkus provides a @QuarkusTest annotation to integrate JUnit tests with the application lifecycle. This allows seamless testing of GraalVM-native applications, ensuring that the same logic works across JVM and native environments.


Examples for JUnit

  1. Basic JUnit Test
@QuarkusTest
public class HelloServiceTest {
    @Inject
    HelloService helloService;

    @Test
    public void testHello() {
        Assertions.assertEquals("Hello, Quarkus!", helloService.greet());
    }
}

This example tests a service method using JUnit with the @QuarkusTest annotation.

  1. Testing Native Image Compatibility
mvn verify -Pnative

This command runs JUnit tests on a native image build, validating its compatibility and functionality.


RestAssured Integration: 2 Key Points

  1. API Testing Simplified
    RestAssured provides an intuitive DSL for testing RESTful APIs in Quarkus applications. Its integration with GraalVM ensures that API tests are fast and resource-efficient, even when testing native images.

  2. Built-In Support for Quarkus
    Quarkus provides native extensions for RestAssured, allowing seamless HTTP request and response testing. This simplifies validating REST endpoints in applications optimized with GraalVM.


Examples for RestAssured

  1. Basic REST API Test
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;

@QuarkusTest
public class HelloResourceTest {
    @Test
    public void testHelloEndpoint() {
        given()
          .when().get("/hello")
          .then()
             .statusCode(200)
             .body(is("Hello, RESTEasy!"));
    }
}

This tests a REST API endpoint using RestAssured.

  1. Testing with Query Parameters
@Test
public void testWithQueryParams() {
    given()
      .queryParam("name", "Quarkus")
      .when().get("/greet")
      .then()
         .statusCode(200)
         .body("message", equalTo("Hello, Quarkus!"));
}

This validates an endpoint that accepts query parameters and checks the response.