View Javadoc
1   package net.avcompris.commons3.web.it.utils;
2   
3   import static com.google.common.base.Preconditions.checkNotNull;
4   import static com.google.common.base.Preconditions.checkState;
5   import static net.avcompris.commons3.web.it.utils.ExpressionUtils.process;
6   import static org.apache.commons.lang3.StringUtils.substringAfter;
7   import static org.apache.commons.lang3.StringUtils.substringBefore;
8   import static org.apache.commons.lang3.StringUtils.substringBetween;
9   
10  import java.io.IOException;
11  
12  import org.junit.jupiter.api.BeforeEach;
13  
14  public abstract class AbstractWebTest {
15  
16  	private static String CURRENT_BASE_URL;
17  
18  	/**
19  	 * Use the "@RestAssured" annotation set on the test class (e.g. AppInfoTest) to
20  	 * retrieve the env property to use for the API baseURL (e.g.
21  	 * "customers.baseURL"), and then call {@link #setUpRestAssured(String)}
22  	 */
23  	@BeforeEach
24  	public final void setUpRestAssured() throws Exception {
25  
26  		final Class<? extends AbstractWebTest> clazz = this.getClass();
27  
28  		final RestAssured restAssuredAnnotation = clazz.getAnnotation(RestAssured.class);
29  
30  		checkState(restAssuredAnnotation != null, //
31  				"Class should be annotated with @RestAssured: %s", clazz.getName());
32  
33  		final String baseURL = process(restAssuredAnnotation.value());
34  
35  		setUpRestAssured(baseURL);
36  	}
37  
38  	/**
39  	 * Set up Rest Assured with the env property to use for the API baseURL (e.g.
40  	 * "${customers.baseURL}"), which should have a value such as
41  	 * "http://localhost:8080/api/v1".
42  	 * 
43  	 * Please use {@link ExpressionUtils#process(String)} if you want to process an
44  	 * expression that uses variables.
45  	 */
46  	public static void setUpRestAssured(final String baseURL) throws IOException {
47  
48  		checkNotNull(baseURL, "baseURL");
49  
50  		if (CURRENT_BASE_URL != null && baseURL.contentEquals(CURRENT_BASE_URL)) {
51  			return;
52  		}
53  
54  		CURRENT_BASE_URL = baseURL;
55  
56  		System.out.println("setUpRestAssured(): baseURL: " + baseURL);
57  
58  		final String baseURI = substringBefore(baseURL, "//") + "//" + substringBetween(baseURL, "//", ":");
59  
60  		System.out.println("  baseURI: " + baseURI);
61  
62  		final String suffix = substringAfter(substringAfter(baseURL, "//"), ":");
63  
64  		final int port = Integer.parseInt(suffix.contains("/") ? substringBefore(suffix, "/") : suffix);
65  
66  		System.out.println("  port: " + port);
67  
68  		io.restassured.RestAssured.baseURI = baseURI;
69  		io.restassured.RestAssured.port = port;
70  	}
71  }