2017-04-07 118 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)