Use random ports for tests

Update remaining tests to use random ports.

Fixes gh-337
This commit is contained in:
Phillip Webb 2014-04-23 19:10:25 +01:00
parent af33cc2b97
commit 4119ef5cf4
10 changed files with 122 additions and 53 deletions

View File

@ -22,6 +22,7 @@ import java.net.URI;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import org.junit.After; import org.junit.After;
import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.springframework.boot.actuate.endpoint.Endpoint; import org.springframework.boot.actuate.endpoint.Endpoint;
import org.springframework.boot.actuate.endpoint.mvc.MvcEndpoint; import org.springframework.boot.actuate.endpoint.mvc.MvcEndpoint;
@ -29,6 +30,7 @@ import org.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfigurati
import org.springframework.boot.autoconfigure.web.DispatcherServletAutoConfiguration; import org.springframework.boot.autoconfigure.web.DispatcherServletAutoConfiguration;
import org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration; import org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration;
import org.springframework.boot.autoconfigure.web.HttpMessageConvertersAutoConfiguration; import org.springframework.boot.autoconfigure.web.HttpMessageConvertersAutoConfiguration;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration; import org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration;
import org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration; import org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration;
import org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext; import org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext;
@ -45,6 +47,7 @@ import org.springframework.http.client.ClientHttpRequest;
import org.springframework.http.client.ClientHttpResponse; import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.SimpleClientHttpRequestFactory; import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.util.SocketUtils;
import org.springframework.util.StreamUtils; import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseBody;
@ -55,7 +58,7 @@ import static org.junit.Assert.assertThat;
/** /**
* Tests for {@link EndpointWebMvcAutoConfiguration}. * Tests for {@link EndpointWebMvcAutoConfiguration}.
* *
* @author Phillip Webb * @author Phillip Webb
* @author Greg Turnquist * @author Greg Turnquist
*/ */
@ -63,6 +66,13 @@ public class EndpointWebMvcAutoConfigurationTests {
private final AnnotationConfigEmbeddedWebApplicationContext applicationContext = new AnnotationConfigEmbeddedWebApplicationContext(); private final AnnotationConfigEmbeddedWebApplicationContext applicationContext = new AnnotationConfigEmbeddedWebApplicationContext();
private static ThreadLocal<Ports> ports = new ThreadLocal<Ports>();
@Before
public void grabPorts() {
ports.set(new Ports());
}
@After @After
public void close() { public void close() {
if (this.applicationContext != null) { if (this.applicationContext != null) {
@ -73,12 +83,13 @@ public class EndpointWebMvcAutoConfigurationTests {
@Test @Test
public void onSamePort() throws Exception { public void onSamePort() throws Exception {
this.applicationContext.register(RootConfig.class, BaseConfiguration.class, this.applicationContext.register(RootConfig.class, BaseConfiguration.class,
ServerPortConfig.class,
EndpointWebMvcAutoConfiguration.class); EndpointWebMvcAutoConfiguration.class);
this.applicationContext.refresh(); this.applicationContext.refresh();
assertContent("/controller", 8080, "controlleroutput"); assertContent("/controller", ports.get().server, "controlleroutput");
assertContent("/endpoint", 8080, "endpointoutput"); assertContent("/endpoint", ports.get().server, "endpointoutput");
assertContent("/controller", 8081, null); assertContent("/controller", ports.get().management, null);
assertContent("/endpoint", 8081, null); assertContent("/endpoint", ports.get().management, null);
this.applicationContext.close(); this.applicationContext.close();
assertAllClosed(); assertAllClosed();
} }
@ -89,10 +100,10 @@ public class EndpointWebMvcAutoConfigurationTests {
BaseConfiguration.class, EndpointWebMvcAutoConfiguration.class, BaseConfiguration.class, EndpointWebMvcAutoConfiguration.class,
ErrorMvcAutoConfiguration.class); ErrorMvcAutoConfiguration.class);
this.applicationContext.refresh(); this.applicationContext.refresh();
assertContent("/controller", 8080, "controlleroutput"); assertContent("/controller", ports.get().server, "controlleroutput");
assertContent("/endpoint", 8080, null); assertContent("/endpoint", ports.get().server, null);
assertContent("/controller", 8081, null); assertContent("/controller", ports.get().management, null);
assertContent("/endpoint", 8081, "endpointoutput"); assertContent("/endpoint", ports.get().management, "endpointoutput");
this.applicationContext.close(); this.applicationContext.close();
assertAllClosed(); assertAllClosed();
} }
@ -107,9 +118,9 @@ public class EndpointWebMvcAutoConfigurationTests {
this.applicationContext.addApplicationListener(grabManagementPort); this.applicationContext.addApplicationListener(grabManagementPort);
this.applicationContext.refresh(); this.applicationContext.refresh();
int managementPort = grabManagementPort.getServletContainer().getPort(); int managementPort = grabManagementPort.getServletContainer().getPort();
assertThat(managementPort, not(equalTo(8080))); assertThat(managementPort, not(equalTo(ports.get().server)));
assertContent("/controller", 8080, "controlleroutput"); assertContent("/controller", ports.get().server, "controlleroutput");
assertContent("/endpoint", 8080, null); assertContent("/endpoint", ports.get().server, null);
assertContent("/controller", managementPort, null); assertContent("/controller", managementPort, null);
assertContent("/endpoint", managementPort, "endpointoutput"); assertContent("/endpoint", managementPort, "endpointoutput");
} }
@ -119,25 +130,25 @@ public class EndpointWebMvcAutoConfigurationTests {
this.applicationContext.register(RootConfig.class, DisableConfig.class, this.applicationContext.register(RootConfig.class, DisableConfig.class,
BaseConfiguration.class, EndpointWebMvcAutoConfiguration.class); BaseConfiguration.class, EndpointWebMvcAutoConfiguration.class);
this.applicationContext.refresh(); this.applicationContext.refresh();
assertContent("/controller", 8080, "controlleroutput"); assertContent("/controller", ports.get().server, "controlleroutput");
assertContent("/endpoint", 8080, null); assertContent("/endpoint", ports.get().server, null);
assertContent("/controller", 8081, null); assertContent("/controller", ports.get().management, null);
assertContent("/endpoint", 8081, null); assertContent("/endpoint", ports.get().management, null);
this.applicationContext.close(); this.applicationContext.close();
assertAllClosed(); assertAllClosed();
} }
@Test @Test
public void specificPortsViaProperties() throws Exception { public void specificPortsViaProperties() throws Exception {
EnvironmentTestUtils.addEnvironment(this.applicationContext, "server.port:7070", EnvironmentTestUtils.addEnvironment(this.applicationContext, "server.port:"
"management.port:7071"); + ports.get().server, "management.port:" + ports.get().management);
this.applicationContext.register(RootConfig.class, BaseConfiguration.class, this.applicationContext.register(RootConfig.class, BaseConfiguration.class,
EndpointWebMvcAutoConfiguration.class, ErrorMvcAutoConfiguration.class); EndpointWebMvcAutoConfiguration.class, ErrorMvcAutoConfiguration.class);
this.applicationContext.refresh(); this.applicationContext.refresh();
assertContent("/controller", 7070, "controlleroutput"); assertContent("/controller", ports.get().server, "controlleroutput");
assertContent("/endpoint", 7070, null); assertContent("/endpoint", ports.get().server, null);
assertContent("/controller", 7071, null); assertContent("/controller", ports.get().management, null);
assertContent("/endpoint", 7071, "endpointoutput"); assertContent("/endpoint", ports.get().management, "endpointoutput");
this.applicationContext.close(); this.applicationContext.close();
assertAllClosed(); assertAllClosed();
} }
@ -146,7 +157,7 @@ public class EndpointWebMvcAutoConfigurationTests {
public void contextPath() throws Exception { public void contextPath() throws Exception {
EnvironmentTestUtils.addEnvironment(this.applicationContext, EnvironmentTestUtils.addEnvironment(this.applicationContext,
"management.contextPath:/test"); "management.contextPath:/test");
this.applicationContext.register(RootConfig.class, this.applicationContext.register(RootConfig.class, ServerPortConfig.class,
PropertyPlaceholderAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class,
ManagementServerPropertiesAutoConfiguration.class, ManagementServerPropertiesAutoConfiguration.class,
ServerPropertiesAutoConfiguration.class, ServerPropertiesAutoConfiguration.class,
@ -155,17 +166,17 @@ public class EndpointWebMvcAutoConfigurationTests {
DispatcherServletAutoConfiguration.class, WebMvcAutoConfiguration.class, DispatcherServletAutoConfiguration.class, WebMvcAutoConfiguration.class,
EndpointWebMvcAutoConfiguration.class); EndpointWebMvcAutoConfiguration.class);
this.applicationContext.refresh(); this.applicationContext.refresh();
assertContent("/controller", 8080, "controlleroutput"); assertContent("/controller", ports.get().server, "controlleroutput");
assertContent("/test/endpoint", 8080, "endpointoutput"); assertContent("/test/endpoint", ports.get().server, "endpointoutput");
this.applicationContext.close(); this.applicationContext.close();
assertAllClosed(); assertAllClosed();
} }
private void assertAllClosed() throws Exception { private void assertAllClosed() throws Exception {
assertContent("/controller", 8080, null); assertContent("/controller", ports.get().server, null);
assertContent("/endpoint", 8080, null); assertContent("/endpoint", ports.get().server, null);
assertContent("/controller", 8081, null); assertContent("/controller", ports.get().management, null);
assertContent("/endpoint", 8081, null); assertContent("/endpoint", ports.get().management, null);
} }
public void assertContent(String url, int port, Object expected) throws Exception { public void assertContent(String url, int port, Object expected) throws Exception {
@ -194,6 +205,14 @@ public class EndpointWebMvcAutoConfigurationTests {
} }
} }
private static class Ports {
int server = SocketUtils.findAvailableTcpPort();
int management = SocketUtils.findAvailableTcpPort();
}
@Configuration @Configuration
@Import({ PropertyPlaceholderAutoConfiguration.class, @Import({ PropertyPlaceholderAutoConfiguration.class,
EmbeddedServletContainerAutoConfiguration.class, EmbeddedServletContainerAutoConfiguration.class,
@ -217,6 +236,19 @@ public class EndpointWebMvcAutoConfigurationTests {
public TestEndpoint testEndpoint() { public TestEndpoint testEndpoint() {
return new TestEndpoint(); return new TestEndpoint();
} }
}
@Configuration
public static class ServerPortConfig {
@Bean
public ServerProperties serverProperties() {
ServerProperties properties = new ServerProperties();
properties.setPort(ports.get().server);
return properties;
}
} }
@Controller @Controller
@ -231,18 +263,20 @@ public class EndpointWebMvcAutoConfigurationTests {
} }
@Configuration @Configuration
@Import(ServerPortConfig.class)
public static class DifferentPortConfig { public static class DifferentPortConfig {
@Bean @Bean
public ManagementServerProperties managementServerProperties() { public ManagementServerProperties managementServerProperties() {
ManagementServerProperties properties = new ManagementServerProperties(); ManagementServerProperties properties = new ManagementServerProperties();
properties.setPort(8081); properties.setPort(ports.get().management);
return properties; return properties;
} }
} }
@Configuration @Configuration
@Import(ServerPortConfig.class)
public static class RandomPortConfig { public static class RandomPortConfig {
@Bean @Bean
@ -255,6 +289,7 @@ public class EndpointWebMvcAutoConfigurationTests {
} }
@Configuration @Configuration
@Import(ServerPortConfig.class)
public static class DisableConfig { public static class DisableConfig {
@Bean @Bean

View File

@ -47,13 +47,13 @@ public class SpringApplicationHierarchyTests {
public void testParent() { public void testParent() {
SpringApplicationBuilder builder = new SpringApplicationBuilder(Child.class); SpringApplicationBuilder builder = new SpringApplicationBuilder(Child.class);
builder.parent(Parent.class); builder.parent(Parent.class);
this.context = builder.run(); this.context = builder.run("--server.port=0");
} }
@Test @Test
public void testChild() { public void testChild() {
this.context = new SpringApplicationBuilder(Parent.class).child(Child.class) this.context = new SpringApplicationBuilder(Parent.class).child(Child.class).run(
.run(); "--server.port=0");
} }
@EnableAutoConfiguration @EnableAutoConfiguration

View File

@ -60,7 +60,8 @@ public class BasicErrorControllerSpecialIntegrationTests {
@Test @Test
public void errorPageAvailableWithParentContext() throws Exception { public void errorPageAvailableWithParentContext() throws Exception {
setup((ConfigurableWebApplicationContext) new SpringApplicationBuilder( setup((ConfigurableWebApplicationContext) new SpringApplicationBuilder(
ParentConfiguration.class).child(ChildConfiguration.class).run()); ParentConfiguration.class).child(ChildConfiguration.class).run(
"--server.port=0"));
MvcResult response = this.mockMvc MvcResult response = this.mockMvc
.perform(get("/error").accept(MediaType.TEXT_HTML)) .perform(get("/error").accept(MediaType.TEXT_HTML))
.andExpect(status().isOk()).andReturn(); .andExpect(status().isOk()).andReturn();
@ -70,8 +71,8 @@ public class BasicErrorControllerSpecialIntegrationTests {
@Test @Test
public void errorPageAvailableWithMvcIncluded() throws Exception { public void errorPageAvailableWithMvcIncluded() throws Exception {
setup((ConfigurableWebApplicationContext) SpringApplication setup((ConfigurableWebApplicationContext) new SpringApplication(
.run(WebMvcIncludedConfiguration.class)); WebMvcIncludedConfiguration.class).run("--server.port=0"));
MvcResult response = this.mockMvc MvcResult response = this.mockMvc
.perform(get("/error").accept(MediaType.TEXT_HTML)) .perform(get("/error").accept(MediaType.TEXT_HTML))
.andExpect(status().isOk()).andReturn(); .andExpect(status().isOk()).andReturn();

View File

@ -20,6 +20,7 @@ import org.junit.After;
import org.junit.Test; import org.junit.Test;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration; import org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration;
import org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration;
import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource; import org.springframework.context.annotation.ImportResource;
@ -48,8 +49,9 @@ public class AutoConfigurationReproTests {
public void doesNotEarlyInitializeFactoryBeans() throws Exception { public void doesNotEarlyInitializeFactoryBeans() throws Exception {
SpringApplication application = new SpringApplication(EarlyInitConfig.class, SpringApplication application = new SpringApplication(EarlyInitConfig.class,
PropertySourcesPlaceholderConfigurer.class, PropertySourcesPlaceholderConfigurer.class,
EmbeddedServletContainerAutoConfiguration.class); EmbeddedServletContainerAutoConfiguration.class,
this.context = application.run(); ServerPropertiesAutoConfiguration.class);
this.context = application.run("--server.port=0");
String bean = (String) this.context.getBean("earlyInit"); String bean = (String) this.context.getBean("earlyInit");
assertThat(bean, equalTo("bucket")); assertThat(bean, equalTo("bucket"));
} }

View File

@ -131,7 +131,9 @@ public class MultipartAutoConfigurationTests {
public void containerWithAutomatedMultipartTomcatConfiguration() throws Exception { public void containerWithAutomatedMultipartTomcatConfiguration() throws Exception {
this.context = new AnnotationConfigEmbeddedWebApplicationContext( this.context = new AnnotationConfigEmbeddedWebApplicationContext(
ContainerWithEverythingTomcat.class, BaseConfiguration.class); ContainerWithEverythingTomcat.class, BaseConfiguration.class);
new RestTemplate().getForObject("http://localhost:8080/", String.class); new RestTemplate().getForObject("http://localhost:"
+ this.context.getEmbeddedServletContainer().getPort() + "/",
String.class);
this.context.getBean(MultipartConfigElement.class); this.context.getBean(MultipartConfigElement.class);
assertSame(this.context.getBean(DispatcherServlet.class).getMultipartResolver(), assertSame(this.context.getBean(DispatcherServlet.class).getMultipartResolver(),
this.context.getBean(StandardServletMultipartResolver.class)); this.context.getBean(StandardServletMultipartResolver.class));
@ -140,8 +142,9 @@ public class MultipartAutoConfigurationTests {
private void verifyServletWorks() { private void verifyServletWorks() {
RestTemplate restTemplate = new RestTemplate(); RestTemplate restTemplate = new RestTemplate();
assertEquals(restTemplate.getForObject("http://localhost:8080/", String.class), assertEquals(restTemplate.getForObject("http://localhost:"
"Hello"); + this.context.getEmbeddedServletContainer().getPort() + "/",
String.class), "Hello");
} }
@Configuration @Configuration
@ -150,6 +153,13 @@ public class MultipartAutoConfigurationTests {
ServerPropertiesAutoConfiguration.class }) ServerPropertiesAutoConfiguration.class })
protected static class BaseConfiguration { protected static class BaseConfiguration {
@Bean
public ServerProperties serverProperties() {
ServerProperties properties = new ServerProperties();
properties.setPort(0);
return properties;
}
} }
@Configuration @Configuration

View File

@ -39,6 +39,7 @@ import org.springframework.boot.cli.command.jar.JarCommand;
import org.springframework.boot.cli.command.run.RunCommand; import org.springframework.boot.cli.command.run.RunCommand;
import org.springframework.boot.cli.command.test.TestCommand; import org.springframework.boot.cli.command.test.TestCommand;
import org.springframework.boot.cli.util.OutputCapture; import org.springframework.boot.cli.util.OutputCapture;
import org.springframework.util.SocketUtils;
/** /**
* {@link TestRule} that can be used to invoke CLI commands. * {@link TestRule} that can be used to invoke CLI commands.
@ -57,6 +58,8 @@ public class CliTester implements TestRule {
private final String prefix; private final String prefix;
private final int port = SocketUtils.findAvailableTcpPort();
public CliTester(String prefix) { public CliTester(String prefix) {
this.prefix = prefix; this.prefix = prefix;
} }
@ -96,11 +99,13 @@ public class CliTester implements TestRule {
@Override @Override
public T call() throws Exception { public T call() throws Exception {
ClassLoader loader = Thread.currentThread().getContextClassLoader(); ClassLoader loader = Thread.currentThread().getContextClassLoader();
System.setProperty("server.port", String.valueOf(CliTester.this.port));
try { try {
command.run(sources); command.run(sources);
return command; return command;
} }
finally { finally {
System.clearProperty("server.port");
Thread.currentThread().setContextClassLoader(loader); Thread.currentThread().setContextClassLoader(loader);
} }
} }
@ -148,12 +153,13 @@ public class CliTester implements TestRule {
} }
public String getHttpOutput() { public String getHttpOutput() {
return getHttpOutput("http://localhost:8080"); return getHttpOutput("/");
} }
public String getHttpOutput(String uri) { public String getHttpOutput(String uri) {
try { try {
InputStream stream = URI.create(uri).toURL().openStream(); InputStream stream = URI.create("http://localhost:" + this.port + uri)
.toURL().openStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String line; String line;
StringBuilder result = new StringBuilder(); StringBuilder result = new StringBuilder();

View File

@ -99,7 +99,7 @@ public class SampleIntegrationTests {
this.cli.run("ui.groovy", "--classpath=.:src/test/resources"); this.cli.run("ui.groovy", "--classpath=.:src/test/resources");
String result = this.cli.getHttpOutput(); String result = this.cli.getHttpOutput();
assertTrue("Wrong output: " + result, result.contains("Hello World")); assertTrue("Wrong output: " + result, result.contains("Hello World"));
result = this.cli.getHttpOutput("http://localhost:8080/css/bootstrap.min.css"); result = this.cli.getHttpOutput("/css/bootstrap.min.css");
assertTrue("Wrong output: " + result, result.contains("container")); assertTrue("Wrong output: " + result, result.contains("container"));
} }

View File

@ -1,8 +1,8 @@
logging.file: /tmp/logs/app.log logging.file: /tmp/logs/app.log
management.port: 8080 #server.port: 8080
#management.port: 8080
management.address: 127.0.0.1 management.address: 127.0.0.1
endpoints.shutdown.enabled: true endpoints.shutdown.enabled: true
server.port: 8080
server.tomcat.basedir: target/tomcat server.tomcat.basedir: target/tomcat
server.tomcat.access_log_pattern: %h %t "%r" %s %b server.tomcat.access_log_pattern: %h %t "%r" %s %b
security.require_ssl: false security.require_ssl: false
@ -14,4 +14,4 @@ shell.ssh.port: 2222
shell.auth: spring shell.auth: spring
#shell.auth: key #shell.auth: key
#shell.auth.key.path: ${user.home}/test/id_rsa.pub.pem #shell.auth.key.path: ${user.home}/test/id_rsa.pub.pem
#shell.auth: simple #shell.auth: simple

View File

@ -31,6 +31,7 @@ import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.ClassPathResource;
import org.springframework.util.FileCopyUtils; import org.springframework.util.FileCopyUtils;
import org.springframework.util.SocketUtils;
/** /**
* Sample Application to show Tomcat running 2 connectors * Sample Application to show Tomcat running 2 connectors
@ -42,6 +43,11 @@ import org.springframework.util.FileCopyUtils;
@ComponentScan @ComponentScan
public class SampleTomcatTwoConnectorsApplication { public class SampleTomcatTwoConnectorsApplication {
@Bean
public int port() {
return SocketUtils.findAvailableTcpPort();
}
@Bean @Bean
public EmbeddedServletContainerFactory servletContainer() { public EmbeddedServletContainerFactory servletContainer() {
TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory(); TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory();
@ -57,7 +63,7 @@ public class SampleTomcatTwoConnectorsApplication {
File truststore = keystore; File truststore = keystore;
connector.setScheme("https"); connector.setScheme("https");
connector.setSecure(true); connector.setSecure(true);
connector.setPort(8443); connector.setPort(port());
protocol.setSSLEnabled(true); protocol.setSSLEnabled(true);
protocol.setKeystoreFile(keystore.getAbsolutePath()); protocol.setKeystoreFile(keystore.getAbsolutePath());
protocol.setKeystorePass("changeit"); protocol.setKeystorePass("changeit");

View File

@ -29,8 +29,11 @@ import javax.net.ssl.X509TrustManager;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.IntegrationTest; import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory; import org.springframework.http.client.SimpleClientHttpRequestFactory;
@ -49,10 +52,16 @@ import static org.junit.Assert.assertEquals;
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = SampleTomcatTwoConnectorsApplication.class) @SpringApplicationConfiguration(classes = SampleTomcatTwoConnectorsApplication.class)
@WebAppConfiguration @WebAppConfiguration
@IntegrationTest @IntegrationTest("server.port=0")
@DirtiesContext @DirtiesContext
public class SampleTomcatTwoConnectorsApplicationTests { public class SampleTomcatTwoConnectorsApplicationTests {
@Value("${local.server.port}")
private String port;
@Autowired
private ApplicationContext context;
@BeforeClass @BeforeClass
public static void setUp() { public static void setUp() {
@ -100,13 +109,13 @@ public class SampleTomcatTwoConnectorsApplicationTests {
}); });
template.setRequestFactory(factory); template.setRequestFactory(factory);
ResponseEntity<String> entity = template.getForEntity( ResponseEntity<String> entity = template.getForEntity("http://localhost:"
"http://localhost:8080/hello", String.class); + this.port + "/hello", String.class);
assertEquals(HttpStatus.OK, entity.getStatusCode()); assertEquals(HttpStatus.OK, entity.getStatusCode());
assertEquals("hello", entity.getBody()); assertEquals("hello", entity.getBody());
ResponseEntity<String> httpsEntity = template.getForEntity( ResponseEntity<String> httpsEntity = template.getForEntity("https://localhost:"
"https://localhost:8443/hello", String.class); + this.context.getBean("port") + "/hello", String.class);
assertEquals(HttpStatus.OK, httpsEntity.getStatusCode()); assertEquals(HttpStatus.OK, httpsEntity.getStatusCode());
assertEquals("hello", httpsEntity.getBody()); assertEquals("hello", httpsEntity.getBody());