测试Spring Boot应用启动

Test the SpringBoot application startup

我有一个 JUnit 测试,它在测试后启动一个 spring-boot 应用程序(在我的例子中,主要的 class 是 SpringTestDemoApp):

@WebIntegrationTest
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = SpringTestDemoApp.class)
public class SpringTest {

    @Test
    public void test() {
        // Test http://localhost:8080/ (with Selenium)
    }
}

使用 spring-boot 1.3.3.RELEASE 一切正常。尽管如此,注释 @WebIntegrationTest@SpringApplicationConfiguration 已在 spring-boot 1.5.2.RELEASE 中删除。我试图将代码重构为新版本,但我做不到。通过以下测试,我的应用在测试之前没有启动并且 http://localhost:8080 returns 404:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringTestDemoApp.class)
@WebAppConfiguration
public class SpringTest {

    @Test
    public void test() {
        // The same test than before
    }

}

如何重构我的测试以使其在 spring-boot 1.5 中运行?

这是我目前正在使用的片段,当然,根据您要使用的网络驱动程序,您可以为其创建不同的 bean。 确保你的 pom.xml:

上有 spring 引导测试和 selenium
    <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>

在我的例子中 ${selenium.version} 是:

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

那些是 类:

@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()));
    }
}

希望对您有所帮助!

无法使用,因为SpringBootTest默认使用随机端口,请使用:

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)

@SpringBootTest里面的webEnvironment选项很重要。它可以采用 NONEMOCKRANDOM_PORTDEFINED_PORT 等值。

  • NONE 只会创建 spring bean,不会模拟 servlet 环境。

  • MOCK 将创建 spring 个 bean 和模拟 servlet 环境。

  • RANDOM_PORT 将在随机端口上启动实际的 servlet 容器;这可以使用 @LocalServerPort.

  • 自动装配
  • DEFINED_PORT 将获取属性中定义的端口并使用它启动服务器。

当你不定义任何 webEnvironment 时,默认为 RANDOM_PORT。因此,该应用程序可能会在您的不同端口启动。

尝试将其覆盖到 DEFINED_PORT,或尝试自动连接端口号并尝试 运行 在该端口上进行测试。