2017-04-07 117 views
2

我有一个启动春季启动应用程序的JUnit测试的测试之后(在我的情况下,主类是SpringTestDemoApp) -boot 1.3.3.RELEASE。不过,注释@WebIntegrationTest@SpringApplicationConfiguration已在春季启动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 
    } 

} 

我如何修改我的测试,使其工作在春季启动1.5吗?

+0

你能看到日志中的任何异常/消息吗? –

回答

4

@SpringBootTestwebEnvironment的选择是非常重要的。它可以采取类似的值NONEMOCKRANDOM_PORTDEFINED_PORT

  • NONE只会造成的Spring bean,而不是任何模拟的servlet环境。

  • MOCK将创建春天豆类和模拟servlet环境。

  • RANDOM_PORT将开始一个随机端口上的实际servlet容器;这可以使用@LocalServerPort自动装配。

  • DEFINED_PORT将在属性定义的端口,并开始使用它的服务器。

默认为RANDOM_PORT,当你不定义任何webEnvironment。因此,该应用可能会为您启动另一个端口。

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

2

这是我目前使用的过程取决于你想用你可以为它创建不同的豆类网络驱动器的一个片段。 确保你有你的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

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

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)