[英]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.