Test the SpringBoot application startup

The webEnvironment option inside @SpringBootTest is very important. It can take values like NONE, MOCK, RANDOM_PORT, DEFINED_PORT.

  • NONE will only create spring beans and not any mock the servlet environment.

  • MOCK will create spring beans and a mock servlet environment.

  • RANDOM_PORT will start the actual servlet container on a random port; this can be autowired using the @LocalServerPort.

  • DEFINED_PORT will take the defined port in the properties and start the server with it.

The default is RANDOM_PORT when you don’t define any webEnvironment. So the app may be starting at a different port for you.

Try to override it to DEFINED_PORT, or try to autowire the port number and try to run test on that port.


It does not work because SpringBootTest uses random port by default, please use:

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)

This is a snippet of what I'm currently using, of course depending on the web-driver you want to use you can create different beans for it. Make sure you have spring boot test and selenium on your pom.xml:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>${selenium.version}</version>
        <scope>test</scope>
    </dependency>

in my case ${selenium.version} is:

<properties>
    <selenium.version>2.53.1</selenium.version>
</properties>

and those are the classes:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@Import(IntegrationConfiguration.class)
public abstract class AbstractSystemIntegrationTest {

    @LocalServerPort
    protected int serverPort;

    @Autowired
    protected WebDriver driver;

    public String getCompleteLocalUrl(String path) {
        return "http://localhost:" + serverPort + path;
    }
}

public class IntegrationConfiguration {

    @Bean
    private WebDriver htmlUnitWebDriver(Environment env) {
        return new HtmlUnitDriver(true);
    }
}


public class MyWhateverIT extends AbstractSystemIntegrationTest {

    @Test
    public void myTest() {
        driver.get(getCompleteLocalUrl("/whatever-path/you/can/have"));
        WebElement title = driver.findElement(By.id("title-id"));
        Assert.assertThat(title, is(notNullValue()));
    }
}

hope it helps!