Link Search Menu Expand Document

Spring

Table of contents

  1. Installation
  2. Usage
    1. Client side validation
    2. Mock MVC tests
  3. License

Installation

Add the following to your pom.xml :

<dependency>
  <groupId>org.openapi4j</groupId>
  <artifactId>openapi-operation-spring</artifactId>
  <!-- for MockMVC testing, not for client side validation: -->
  <scope>test</scope>
</dependency>

Release version Snapshot version

Usage

Client side validation

Client side validation of requests and reponses using an interceptor for the RestTemplate.

Resource spec = new ClassPathResource("openapi3.yaml");
RestTemplate client = new RestTemplate();
// add the open API interceptor, should be the last in case of multiple interceptors
client.setInterceptors(Collections.singletonList(OpenApiClientInterceptor.openApi(spec)));

Mock MVC tests

Mock MVC tests get automatic request and response validation. A dependency of spring-test is needed and openapi-operation-spring can also be of scope test if client validation is not needed.

// Test setup
Resource spec = new ClassPathResource("openapi3.yaml");
MockMvc mvc = MockMvcBuilders.standaloneSetup(new TestController())
  .apply(OpenApiMatchers.openApi(spec)) // customize for request and response validation
  .build()

// Test
  mvc.perform(get("/examples")) // perform fails for an undocumented request
  // always expect a documented response first
  .andExpect(status().isOk());
Library Version Client Server Dependency
Spring >= 5.0 ClientRequest, ClientResponse MvcRequest, MvcResponse The Spring web/test dependency you use

License

See main page