7. Generating Contracts using RestDocs
Prev |  | Next

# 7. Generating Contracts using RestDocs

Another thing that can be generated with Spring RestDocs is the Spring Cloud Contract DSL file and documentation. If you combine that with Spring Cloud WireMock then you’re getting both the contracts and stubs.

Why would you want to use this feature? Some people in the community asked questions about situation in which they would like to move to DSL based contract definition but they already have a lot of Spring MVC tests. Using this feature allows you to generate the contract files that you can later modify and move to proper folders so that the plugin picks them up.

| Tip
You might wonder why this functionality is in the WireMock module. Come to think of it, it does make sense since it makes little sense to generate only contracts and not generate the stubs. That’s why we suggest to do both.

Let’s imagine the following test:

    		this.mockMvc.perform(post("/foo")
    					.accept(MediaType.APPLICATION_PDF)
    					.accept(MediaType.APPLICATION_JSON)
    					.contentType(MediaType.APPLICATION_JSON)
    					.content("{\"foo\": 23 }"))
    				.andExpect(status().isOk())
    				.andExpect(content().string("bar"))
    				// first WireMock
    				.andDo(WireMockRestDocs.verify()
    						.jsonPath("$[?(@.foo >= 20)]")
    						.contentType(MediaType.valueOf("application/json"))
    						.stub("shouldGrantABeerIfOldEnough"))
    				// then Contract DSL documentation
    				.andDo(document("index", SpringCloudContractRestDocs.dslContract()));

This will lead in the creation of the stub as presented in the previous section, contract will get generated and a documentation file too.

The contract will be called `index.groovy` and look more like this.

    import org.springframework.cloud.contract.spec.Contract

    Contract.make {
        request {
            method 'POST'
            url '/foo'
            body('''
                {"foo": 23 }
            ''')
            headers {
                header('''Accept''', '''application/json''')
                header('''Content-Type''', '''application/json''')
            }
        }
        response {
            status 200
            body('''
            bar
            ''')
            headers {
                header('''Content-Type''', '''application/json;charset=UTF-8''')
                header('''Content-Length''', '''3''')
            }
            testMatchers {
                jsonPath('$[?(@.foo >= 20)]', byType())
            }
        }
    }

the generated document (example for Asciidoc) will contain a formatted contract (the location of this file would be `index/dsl-contract.adoc`).

Prev |  | Next
6. Generating Stubs using RestDocs | Home | 8. Migrations