测试启动Spring-boot应用程序

时间:2017-04-07 15:02:53

标签: java spring spring-boot junit spring-test

我有一个JUnit测试,在测试后启动一个spring-boot应用程序(在我的例子中,主类是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返回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中运行?

3 个答案:

答案 0 :(得分:7)

webEnvironment内的@SpringBootTest选项非常重要。它可以采用NONEMOCKRANDOM_PORTDEFINED_PORT等值。

  • NONE只会创建spring bean而不是任何模拟servlet环境。

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

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

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

如果您未定义任何RANDOM_PORT,则默认值为webEnvironment。因此,应用可能会在不同的端口为您启动。

尝试将其覆盖为DEFINED_PORT,或尝试自动装配端口号并尝试在该端口上运行测试。

答案 1 :(得分:2)

这是我目前正在使用的片段,当然,根据您要使用的网络驱动程序,您可以为它创建不同的bean。 确保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>

在我的情况下${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()));
    }
}
希望它有所帮助!

答案 2 :(得分:2)

它不起作用,因为SpringBootTest默认使用随机端口,请使用:

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
相关问题