package com.brodwall.kata.webcrud; import static org.fest.assertions.Assertions.*; import org.h2.jdbcx.JdbcDataSource; import org.junit.Before; import org.junit.Test; import org.mortbay.jetty.Server; import org.mortbay.jetty.plus.naming.Resource; import org.mortbay.jetty.webapp.WebAppContext; import org.openqa.selenium.By; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.htmlunit.HtmlUnitDriver; public class PersonWebTest { private WebDriver driver = getDriver(); private String rootUrl; @Before public void startServer() throws Exception { String url = "jdbc:h2:mem:servlet-test;MVCC=true"; HibernatePersonDao.createInMemoryDao(url); JdbcDataSource datasource = new JdbcDataSource(); datasource.setURL(url); new Resource("jdbc/primaryDs", datasource); Server server = new Server(0); server.addHandler(new WebAppContext("src/main/webapp", "/")); server.start(); rootUrl = "http://localhost:" + server.getConnectors()[0].getLocalPort() + "/"; } private WebDriver getDriver() { String webDriverClass = System.getProperty("org.openqa.selenium.WebDriver"); if (webDriverClass != null) { try { return (WebDriver) Class.forName(webDriverClass).newInstance(); } catch (Exception e) { throw new RuntimeException("Could not create " + webDriverClass, e); } } return new HtmlUnitDriver() { @Override public WebElement findElement(By by) { try { return super.findElement(by); } catch (NoSuchElementException e) { throw new NoSuchElementException("Could not find " + by + " in " + getPageSource()); } } }; } @Test public void shouldSearchByName() { driver.get(rootUrl); createPerson("Johannes Brodwall"); createPerson("Johannes Kepler"); createPerson("Ada Brodwall"); assertThat(driver.findElement(By.tagName("title")).getText()).isEqualTo("Show people"); driver.findElement(By.name("name_query")).sendKeys("brodwall"); driver.findElement(By.name("search")).click(); driver.findElement(byText("Johannes Brodwall")); driver.findElement(byText("Ada Brodwall")); assertThat(driver.findElements(byText("Johannes Kepler"))).isEmpty(); } private void createPerson(String personName) { driver.findElement(By.linkText("Create a new person")).click(); driver.findElement(By.name("full_name")).sendKeys(personName); driver.findElement(By.name("create")).click(); } private By byText(String text) { return By.xpath(".//*[text() = '" + text + "']"); } }