All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.jayway.restassured.module.mockmvc.RestAssuredMockMvc Maven / Gradle / Ivy

There is a newer version: 2.9.0
Show newest version
package com.jayway.restassured.module.mockmvc;

import com.jayway.restassured.config.LogConfig;
import com.jayway.restassured.filter.log.LogDetail;
import com.jayway.restassured.module.mockmvc.config.RestAssuredMockMvcConfig;
import com.jayway.restassured.module.mockmvc.internal.MockMvcRequestSpecificationImpl;
import com.jayway.restassured.module.mockmvc.response.MockMvcResponse;
import com.jayway.restassured.module.mockmvc.specification.MockMvcAuthenticationScheme;
import com.jayway.restassured.module.mockmvc.specification.MockMvcRequestSender;
import com.jayway.restassured.module.mockmvc.specification.MockMvcRequestSpecification;
import com.jayway.restassured.specification.ResponseSpecification;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultHandler;
import org.springframework.test.web.servlet.setup.AbstractMockMvcBuilder;
import org.springframework.test.web.servlet.setup.DefaultMockMvcBuilder;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import java.net.URI;
import java.net.URL;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import static com.jayway.restassured.config.LogConfig.logConfig;
import static com.jayway.restassured.internal.assertion.AssertParameter.notNull;

/**
 * The Spring MVC module's equivalent of {@link com.jayway.restassured.RestAssured}. This is the starting point of the DSL.
 * 

Note that some Javadoc is copied from Spring MVC's test documentation.

*/ public class RestAssuredMockMvc { /** * Set a {@link org.springframework.test.web.servlet.MockMvc} instance that REST Assured will use when making requests unless overwritten * by a {@link com.jayway.restassured.module.mockmvc.specification.MockMvcRequestSpecification}. */ public static MockMvc mockMvc = null; /** * Define a REST Assured Mock Mvc configuration. E.g. *
     * given().config(newConfig().logConfig(new LogConfig(captor, true))). ..
     * 
*

* newConfig() can be statically imported from {@link com.jayway.restassured.module.mockmvc.config.RestAssuredMockMvcConfig}. */ public static RestAssuredMockMvcConfig config; /** * Specify a default request specification that will be sent with each request. E,g. *

     * RestAssuredMockMvc.requestSpecification = new MockMvcRequestSpecBuilder().addParam("parameter1", "value1").build();
     * 
*

* means that for each request by Rest Assured "parameter1" will be equal to "value1". */ public static MockMvcRequestSpecification requestSpecification; /** * Specify a default response specification that will be sent with each request. E,g. *

     * RestAssuredMockMvc.responseSpecification = new ResponseSpecBuilder().expectStatusCode(200).build();
     * 
*

* means that for each response Rest Assured will assert that the status code is equal to 200. */ public static ResponseSpecification responseSpecification = null; private static List resultHandlers = new ArrayList(); /** * The base path that's used by REST assured when making requests. The base path is prepended to the request path. * Default value is /. */ public static String basePath = "/"; /** * Defines a global authentication scheme that'll be used for all requests (if not overridden). Usage example: *

     * RestAssured.authentication = principal(myPrincipal);
     * 
* * @see #principal(java.security.Principal) * @see #principal(Object) * @see #principalWithCredentials(Object, Object, String...) * @see #authentication(Object) */ public static MockMvcAuthenticationScheme authentication; /** * This is usually the entry-point of the API if you need to specify parameters or a body in the request. For example: *

*

     * given().
     *         param("x", "y").
     * when().
     *         get("/something").
     * then().
     *        statusCode(200).
     *        body("x.y", notNullValue());
     * 
* Note that this method is the same as {@link #with()} but with another syntax. * * @return A {@link MockMvcRequestSpecification}. */ public static MockMvcRequestSpecification given() { return new MockMvcRequestSpecificationImpl(mockMvc, config, resultHandlers, basePath, requestSpecification, responseSpecification, authentication); } /** * This is usually the entry-point of the API if you need to specify parameters or a body in the request. For example: *

*

     * given().
     *         param("x", "y").
     * when().
     *         get("/something").
     * then().
     *        statusCode(200).
     *        body("x.y", notNullValue());
     * 
*

* Note that this method is the same as {@link #given()} but with another syntax. * * @return A {@link MockMvcRequestSpecification}. */ public static MockMvcRequestSpecification with() { return given(); } /** * This is usually the entry-point of the API if you need to specify parameters or a body in the request. For example: *

*

     * when().
     *        get("/x").
     * then().
     *        body("x.y.z1", equalTo("Z1")).
     *        body("x.y.z2", equalTo("Z2"));
     * 
*

* Note that if you need to add parameters, headers, cookies or other request properties use the {@link #given()} method. *

* * @return A request sender interface that let's you call resources on the server */ public static MockMvcRequestSender when() { return given().when(); } /** * Build a {@link MockMvc} by registering one or more {@code @Controller}'s * instances and configuring Spring MVC infrastructure programmatically. * This allows full control over the instantiation and initialization of * controllers, and their dependencies, similar to plain unit tests while * also making it possible to test one controller at a time. *

*

When this option is used, the minimum infrastructure required by the * {@link org.springframework.web.servlet.DispatcherServlet} to serve requests with annotated controllers is * automatically created, and can be customized, resulting in configuration * that is equivalent to what the MVC Java configuration provides except * using builder style methods. *

*

If the Spring MVC configuration of an application is relatively * straight-forward, for example when using the MVC namespace or the MVC * Java config, then using this builder might be a good option for testing * a majority of controllers. A much smaller number of tests can be used * to focus on testing and verifying the actual Spring MVC configuration. * * @param controllers one or more {@link org.springframework.stereotype.Controller @Controller}'s to test */ public static void standaloneSetup(Object... controllers) { mockMvc = MockMvcBuilders.standaloneSetup(controllers).build(); } /** * Build a {@link MockMvc} by using a provided {@code AbstractMockMvcBuilder} * for configuring Spring MVC infrastructure programmatically. * This allows full control over the instantiation and initialization of * controllers, and their dependencies, similar to plain unit tests while * also making it possible to test one controller at a time. *

*

If the Spring MVC configuration of an application is relatively * straight-forward, for example when using the MVC namespace or the MVC * Java config, then using this builder might be a good option for testing * a majority of controllers. A much smaller number of tests can be used * to focus on testing and verifying the actual Spring MVC configuration. * * @param builder {@link org.springframework.test.web.servlet.setup.AbstractMockMvcBuilder} to build the MVC mock */ public static void standaloneSetup(AbstractMockMvcBuilder builder) { mockMvc = builder.build(); } /** * Build a {@link MockMvc} using the given, fully initialized, i.e. * refreshed, {@link WebApplicationContext} and assign it to REST Assured. * The {@link org.springframework.web.servlet.DispatcherServlet} * will use the context to discover Spring MVC infrastructure and * application controllers in it. The context must have been configured with * a {@link javax.servlet.ServletContext}. */ public static void webAppContextSetup(WebApplicationContext context) { DefaultMockMvcBuilder builder = MockMvcBuilders.webAppContextSetup(context); // To avoid compile-time errors mockMvc = builder.build(); } /** * Assign one or more {@link org.springframework.test.web.servlet.ResultHandler} that'll be executes after a request has been made. * * @param resultHandler The result handler * @param resultHandlers Additional result handlers (optional) */ public static void resultHandlers(ResultHandler resultHandler, ResultHandler... resultHandlers) { notNull(resultHandler, ResultHandler.class); RestAssuredMockMvc.resultHandlers.add(resultHandler); if (resultHandlers != null && resultHandlers.length >= 1) { Collections.addAll(RestAssuredMockMvc.resultHandlers, resultHandlers); } } /** * @return The defined list of result handlers */ public static List resultHandlers() { return Collections.unmodifiableList(resultHandlers); } /** * Reset all static configurations to their default values. */ public static void reset() { mockMvc = null; config = null; basePath = "/"; resultHandlers.clear(); responseSpecification = null; requestSpecification = null; authentication = null; } /** * Perform a GET request to a path. Normally the path doesn't have to be fully-qualified e.g. you don't need to * specify the path as http://localhost:8080/path. In this case it's enough to use /path. * * @param path The path to send the request to. * @param pathParams The path parameters. E.g. if path is "/book/{hotelId}/{roomNumber}" you can do get("/book/{hotelName}/{roomNumber}", "Hotels R Us", 22);. * @return The response of the GET request. */ public static MockMvcResponse get(String path, Object... pathParams) { return given().get(path, pathParams); } /** * Perform a GET request to a path. Normally the path doesn't have to be fully-qualified e.g. you don't need to * specify the path as http://localhost:8080/path. In this case it's enough to use /path. * * @param path The path to send the request to. * @param pathParams The path parameters. * @return The response of the GET request. */ public static MockMvcResponse get(String path, Map pathParams) { return given().get(path, pathParams); } /** * Perform a POST request to a path. Normally the path doesn't have to be fully-qualified e.g. you don't need to * specify the path as http://localhost:8080/path. In this case it's enough to use /path. * * @param path The path to send the request to. * @param pathParams The path parameters. E.g. if path is "/book/{hotelId}/{roomNumber}" you can do post("/book/{hotelName}/{roomNumber}", "Hotels R Us", 22);. * @return The response of the request. */ public static MockMvcResponse post(String path, Object... pathParams) { return given().post(path, pathParams); } /** * Perform a POST request to a path. Normally the path doesn't have to be fully-qualified e.g. you don't need to * specify the path as http://localhost:8080/path. In this case it's enough to use /path. * * @param path The path to send the request to. * @param pathParams The path parameters. * @return The response of the request. */ public static MockMvcResponse post(String path, Map pathParams) { return given().post(path, pathParams); } /** * Perform a PUT request to a path. Normally the path doesn't have to be fully-qualified e.g. you don't need to * specify the path as http://localhost:8080/path. In this case it's enough to use /path. * * @param path The path to send the request to. * @param pathParams The path parameters. E.g. if path is "/book/{hotelId}/{roomNumber}" you can do put("/book/{hotelName}/{roomNumber}", "Hotels R Us", 22);. * @return The response of the request. */ public static MockMvcResponse put(String path, Object... pathParams) { return given().put(path, pathParams); } /** * Perform a DELETE request to a path. Normally the path doesn't have to be fully-qualified e.g. you don't need to * specify the path as http://localhost:8080/path. In this case it's enough to use /path. * * @param path The path to send the request to. * @param pathParams The path parameters. E.g. if path is "/book/{hotelId}/{roomNumber}" you can do delete("/book/{hotelName}/{roomNumber}", "Hotels R Us", 22);. * @return The response of the request. */ public static MockMvcResponse delete(String path, Object... pathParams) { return given().delete(path, pathParams); } /** * Perform a DELETE request to a path. Normally the path doesn't have to be fully-qualified e.g. you don't need to * specify the path as http://localhost:8080/path. In this case it's enough to use /path. * * @param path The path to send the request to. * @param pathParams The path parameters. * @return The response of the request. */ public static MockMvcResponse delete(String path, Map pathParams) { return given().delete(path, pathParams); } /** * Perform a HEAD request to a path. Normally the path doesn't have to be fully-qualified e.g. you don't need to * specify the path as http://localhost:8080/path. In this case it's enough to use /path. * * @param path The path to send the request to. * @param pathParams The path parameters. E.g. if path is "/book/{hotelId}/{roomNumber}" you can do head("/book/{hotelName}/{roomNumber}", "Hotels R Us", 22);. * @return The response of the request. */ public static MockMvcResponse head(String path, Object... pathParams) { return given().head(path, pathParams); } /** * Perform a HEAD request to a path. Normally the path doesn't have to be fully-qualified e.g. you don't need to * specify the path as http://localhost:8080/path. In this case it's enough to use /path. * * @param path The path to send the request to. * @param pathParams The path parameters. * @return The response of the request. */ public static MockMvcResponse head(String path, Map pathParams) { return given().head(path, pathParams); } /** * Perform a PATCH request to a path. Normally the path doesn't have to be fully-qualified e.g. you don't need to * specify the path as http://localhost:8080/path. In this case it's enough to use /path. * * @param path The path to send the request to. * @param pathParams The path parameters. E.g. if path is "/book/{hotelId}/{roomNumber}" you can do head("/book/{hotelName}/{roomNumber}", "Hotels R Us", 22);. * @return The response of the request. */ public static MockMvcResponse patch(String path, Object... pathParams) { return given().patch(path, pathParams); } /** * Perform a PATCH request to a path. Normally the path doesn't have to be fully-qualified e.g. you don't need to * specify the path as http://localhost:8080/path. In this case it's enough to use /path. * * @param path The path to send the request to. * @param pathParams The path parameters. * @return The response of the request. */ public static MockMvcResponse patch(String path, Map pathParams) { return given().patch(path, pathParams); } /** * Perform a OPTIONS request to a path. Normally the path doesn't have to be fully-qualified e.g. you don't need to * specify the path as http://localhost:8080/path. In this case it's enough to use /path. * * @param path The path to send the request to. * @param pathParams The path parameters. E.g. if path is "/book/{hotelId}/{roomNumber}" you can do head("/book/{hotelName}/{roomNumber}", "Hotels R Us", 22);. * @return The response of the request. */ public static MockMvcResponse options(String path, Object... pathParams) { return given().options(path, pathParams); } /** * Perform a OPTIONS request to a path. Normally the path doesn't have to be fully-qualified e.g. you don't need to * specify the path as http://localhost:8080/path. In this case it's enough to use /path. * * @param path The path to send the request to. * @param pathParams The path parameters. * @return The response of the request. */ public static MockMvcResponse options(String path, Map pathParams) { return given().options(path, pathParams); } /** * Perform a GET request to a uri. * * @param uri The uri to send the request to. * @return The response of the GET request. */ public static MockMvcResponse get(URI uri) { return given().get(uri); } /** * Perform a POST request to a uri. * * @param uri The uri to send the request to. * @return The response of the request. */ public static MockMvcResponse post(URI uri) { return given().post(uri); } /** * Perform a PUT request to a uri. * * @param uri The uri to send the request to. * @return The response of the request. */ public static MockMvcResponse put(URI uri) { return given().put(uri); } /** * Perform a DELETE request to a uri. * * @param uri The uri to send the request to. * @return The response of the request. */ public static MockMvcResponse delete(URI uri) { return given().delete(uri); } /** * Perform a HEAD request to a uri. * * @param uri The uri to send the request to. * @return The response of the request. */ public static MockMvcResponse head(URI uri) { return given().head(uri); } /** * Perform a PATCH request to a uri. * * @param uri The uri to send the request to. * @return The response of the request. */ public static MockMvcResponse patch(URI uri) { return given().patch(uri); } /** * Perform a OPTIONS request to a uri. * * @param uri The uri to send the request to. * @return The response of the request. */ public static MockMvcResponse options(URI uri) { return given().options(uri); } /** * Perform a GET request to a url. * * @param url The url to send the request to. * @return The response of the GET request. */ public static MockMvcResponse get(URL url) { return given().get(url); } /** * Perform a POST request to a url. * * @param url The url to send the request to. * @return The response of the request. */ public static MockMvcResponse post(URL url) { return given().post(url); } /** * Perform a PUT request to a url. * * @param url The url to send the request to. * @return The response of the request. */ public static MockMvcResponse put(URL url) { return given().put(url); } /** * Perform a DELETE request to a url. * * @param url The url to send the request to. * @return The response of the request. */ public static MockMvcResponse delete(URL url) { return given().delete(url); } /** * Perform a HEAD request to a url. * * @param url The url to send the request to. * @return The response of the request. */ public static MockMvcResponse head(URL url) { return given().head(url); } /** * Perform a PATCH request to a url. * * @param url The url to send the request to. * @return The response of the request. */ public static MockMvcResponse patch(URL url) { return given().patch(url); } /** * Perform a OPTIONS request to a url. * * @param url The url to send the request to. * @return The response of the request. */ public static MockMvcResponse options(URL url) { return given().options(url); } /** * Perform a GET request to the statically configured base path. * * @return The response of the GET request. */ public static MockMvcResponse get() { return given().get(); } /** * Perform a POST request to the statically configured base path. * * @return The response of the request. */ public static MockMvcResponse post() { return given().post(); } /** * Perform a PUT request to the statically configured base path. * * @return The response of the request. */ public static MockMvcResponse put() { return given().put(); } /** * Perform a DELETE request to the statically configured base path. * * @return The response of the request. */ public static MockMvcResponse delete() { return given().delete(); } /** * Perform a HEAD request to the statically configured base path. * * @return The response of the request. */ public static MockMvcResponse head() { return given().head(); } /** * Perform a PATCH request to the statically configured base path. * * @return The response of the request. */ public static MockMvcResponse patch() { return given().patch(); } /** * Perform a OPTIONS request to the statically configured base path. * * @return The response of the request. */ public static MockMvcResponse options() { return given().options(); } /** * Authenticate using the given principal. Used as: *

     * RestAssured.authentication = principal(myPrincipal);
     * 
* or in a {@link com.jayway.restassured.module.mockmvc.specification.MockMvcRequestSpecBuilder}: *
     * MockMvcRequestSpecification req = new MockMvcRequestSpecBuilder().setAuth(principal(myPrincipal)). ..
     * 
* * @param principal The principal to use. * @return A {@link com.jayway.restassured.module.mockmvc.specification.MockMvcAuthenticationScheme} instance. * @see com.jayway.restassured.module.mockmvc.specification.MockMvcAuthenticationSpecification#principal(java.security.Principal) */ public static MockMvcAuthenticationScheme principal(final Principal principal) { return new MockMvcAuthenticationScheme() { public void authenticate(MockMvcRequestSpecification mockMvcRequestSpecification) { mockMvcRequestSpecification.auth().principal(principal); } }; } /** * Authenticate using the given principal. Used as: *
     * RestAssured.authentication = principal(myPrincipal);
     * 
* or in a {@link com.jayway.restassured.module.mockmvc.specification.MockMvcRequestSpecBuilder}: *
     * MockMvcRequestSpecification req = new MockMvcRequestSpecBuilder().setAuth(principal(myPrincipal)). ..
     * 
* * @param principal The principal to use. * @return A {@link com.jayway.restassured.module.mockmvc.specification.MockMvcAuthenticationScheme} instance. * @see com.jayway.restassured.module.mockmvc.specification.MockMvcAuthenticationSpecification#principal(Object) */ public static MockMvcAuthenticationScheme principal(final Object principal) { return new MockMvcAuthenticationScheme() { public void authenticate(MockMvcRequestSpecification mockMvcRequestSpecification) { mockMvcRequestSpecification.auth().principal(principal); } }; } /** * Authenticate using the given principal and credentials. Used as: *
     * RestAssured.authentication = principalWithCredentials(myPrincipal, myCredentials);
     * 
* or in a {@link com.jayway.restassured.module.mockmvc.specification.MockMvcRequestSpecBuilder}: *
     * MockMvcRequestSpecification req = new MockMvcRequestSpecBuilder().setAuth(principalWithCredentials(myPrincipal, myCredentials)). ..
     * 
* * @param principal The principal to use. * @param credentials The credentials to use * @param authorities Optional list of authorities * @return A {@link com.jayway.restassured.module.mockmvc.specification.MockMvcAuthenticationScheme} instance. * @see com.jayway.restassured.module.mockmvc.specification.MockMvcAuthenticationSpecification#principalWithCredentials(Object, Object, String...) */ public static MockMvcAuthenticationScheme principalWithCredentials(final Object principal, final Object credentials, final String... authorities) { return new MockMvcAuthenticationScheme() { public void authenticate(MockMvcRequestSpecification mockMvcRequestSpecification) { mockMvcRequestSpecification.auth().principalWithCredentials(principal, credentials, authorities); } }; } /** * Authenticate using the supplied authentication instance (org.springframework.security.core.Authentication from Spring Security). Used as: *
     * RestAssured.authentication = authentication(myAuth);
     * 
* or in a {@link com.jayway.restassured.module.mockmvc.specification.MockMvcRequestSpecBuilder}: *
     * MockMvcRequestSpecification req = new MockMvcRequestSpecBuilder().setAuth(authentication(myAuth)). ..
     * 
* * @param authentication The authentication instance to use. * @return A {@link com.jayway.restassured.module.mockmvc.specification.MockMvcAuthenticationScheme} instance. * @see com.jayway.restassured.module.mockmvc.specification.MockMvcAuthenticationSpecification#authentication(Object) */ public static MockMvcAuthenticationScheme authentication(final Object authentication) { return new MockMvcAuthenticationScheme() { public void authenticate(MockMvcRequestSpecification mockMvcRequestSpecification) { mockMvcRequestSpecification.auth().authentication(authentication); } }; } /** * Enable logging of both the request and the response if REST Assureds test validation fails with log detail equal to {@link com.jayway.restassured.filter.log.LogDetail#ALL}. *

*

* This is just a shortcut for: *

*
     * RestAssuredMockMvc.config = new RestAssuredMockMvcConfig().logConfig(logConfig().enableLoggingOfRequestAndResponseIfValidationFails());
     * 
*/ public static void enableLoggingOfRequestAndResponseIfValidationFails() { enableLoggingOfRequestAndResponseIfValidationFails(LogDetail.ALL); } /** * Enable logging of both the request and the response if REST Assureds test validation fails with the specified log detail. *

*

* This is just a shortcut for: *

*
     * RestAssured.config = new RestAssuredMockMvcConfig().logConfig(logConfig().enableLoggingOfRequestAndResponseIfValidationFails(logDetail));
     * 
* * @param logDetail The log detail to show in the log */ public static void enableLoggingOfRequestAndResponseIfValidationFails(LogDetail logDetail) { config = config == null ? new RestAssuredMockMvcConfig() : config; config = config.logConfig(logConfig().enableLoggingOfRequestAndResponseIfValidationFails(logDetail)); // Update request specification if already defined otherwise it'll override the configs. // Note that request spec also influence response spec when it comes to logging if validation fails due to the way filters work if (requestSpecification != null && requestSpecification instanceof MockMvcRequestSpecificationImpl) { RestAssuredMockMvcConfig restAssuredConfig = ((MockMvcRequestSpecificationImpl) requestSpecification).getRestAssuredMockMvcConfig(); if (restAssuredConfig == null) { restAssuredConfig = config; } else { LogConfig logConfigForRequestSpec = restAssuredConfig.getLogConfig().enableLoggingOfRequestAndResponseIfValidationFails(logDetail); restAssuredConfig = restAssuredConfig.logConfig(logConfigForRequestSpec); } requestSpecification.config(restAssuredConfig); } } }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy