[英]Spring MVC Integration Test with Selenium
我想使用Selenium在SpringMVC應用程序上進行集成測試,例如:
@Test
public void mytest() {
WebDriver driver = new FirefoxDriver();
driver.get("localhost:8080/myapp/mycontroller");
List<WebElement> elements = driver.findElements(By.cssSelector(".oi"));
assertThat(elements, hasSize(1));
}
是否可以像我的mvn tomcat7:run
那樣“運行”我的應用程序,然后執行我的硒測試?
我正在使用Spring4.0.x。 我的Web應用程序上的每個類都已經有單元測試,但是我需要一個集成測試。 我的控制器已經通過MockMVC和spring-test-framework進行了測試...但是我想進行硒集成測試。
經過大量嘗試,我最終完成了Selenium Integration測試的基類:
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.WebAppContext;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.openqa.selenium.firefox.FirefoxDriver;
import static io.github.seleniumquery.SeleniumQuery.$;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
public class SeleniumAcceptanceTest {
private static final String WEBAPP_FOLDER = "../../src/main/webapp";
private static final String APP_CONTEXT = "/myapp";
private static final int ANY_RANDOM_PORT_AVAIABLE = 0;
static Server server;
protected static String urlBase;
@BeforeClass
public static void prepareTests() throws Exception {
startWebAppServer();
$.browser.setDefaultDriver(new FirefoxDriver());
}
@AfterClass
public static void finalizaTests() {
$.browser.quitDefaultBrowser();
}
private static void levantarServidorDeAplicacao() throws Exception {
server = new Server(QUALQUER_PORTA_DISPONIVEL);
String rootPath = SeleniumAcceptanceTest.class.getClassLoader().getResource(".").toString();
WebAppContext webapp = new WebAppContext(rootPath + WEBAPP_FOLDER , "");
webapp.setContextPath(APP_CONTEXT );
server.setHandler(webapp);
server.start();
while (true) {
if (server != null && server.isStarted()) {
break;
}
}
int port = server.getConnectors()[0].getLocalPort();
urlBase = "http://localhost:" + port + APP_CONTEXT ;
}
}
然后,一個測試類擴展了該類:
public class AlertasAcceptanceTest extends SeleniumAcceptanceTest {
@Test
public void alertas_index__must_show_table_with_4_lines() {
//given
doLogin();
//when
$.browser.openUrl(urlBase + "/alertas/" );
int linesInTheTable = $("table tr").size();
//then
assertThat(linesInTheTable , is(4));
}
}
我討厭用一個問題回答一個問題,但是... 1)您必須使用Selenium還是jUnit測試? 2)您使用哪個版本的Spring MVC? Spring 3.2添加了一個非常簡潔的功能,使您可以啟動模擬MVC並對其執行HTTP請求。 這樣,您就不必擔心啟動/停止服務器,並且所有測試都可以在應用本身內部完成。 這是一個片段:
@Test
public void addAsUser() throws Exception {
TodoDTO added = TodoTestUtil.createDTO(null, "description", "title");
mockMvc.perform(post("/api/todo")
.contentType(IntegrationTestUtil.APPLICATION_JSON_UTF8)
.content(IntegrationTestUtil.convertObjectToJsonBytes(added))
.with(userDetailsService("user"))
)
.andExpect(status().isOk())
.andExpect(content().contentType(IntegrationTestUtil.APPLICATION_JSON_UTF8))
.andExpect(content().string("{\"id\":3,\"description\":\"description\",\"title\":\"title\"}"));
}
全文可以在這里找到。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.