There are couple tools that can be used to test generated html and client-side scripts. The most accurate tools are these that run test in the real browser ( for example, Selenium framework ), but, in the some cases, they cannot be used – machine that runs tests has to have GUI ( rare available on continuous integration servers ), preconfigured instances of target browsers, and these tests can take too much time because you have to start new browser instance for each test to eliminate dependencies between them.
Another option is client emulator, that only simulates target browser. Although it’s less accurate then the real browser, the advantages are: no additional software required, it runs faster, and test code has full control on test client configuration. For developer tests in RichFaces, we use HtmlUnit library, integrated with our embedded FacesEnvironment.
Usage
Dependencies
HtmlUnit teste require these dependencies :
Test Project
+- org.jboss.test-jsf:jsf-test-stage
+- org.jboss.test-jsf:jsf-test-jetty ( optional )
+- org.jboss.test-jsf:htmlunit-client
+- javax.servlet:servlet-api
+- javax.servlet.jsp:jsp-api
+- javax.el:el-api
+- javax.servlet:jstl
+- junit:junit
+- com.sun.faces:jsf-api
\- com.sun.faces:jsf-impl ( or any other you want to test with ).
htmlunit-client does not contain dependencies for servlet or JSF because it can be used with different versions and implementations.
HtmlUnitEnvironment
public class FacesTest { private HtmlUnitEnvironment environment; @Before public void setUp() throws Exception { this.environment = new HtmlUnitEnvironment(); this.environment.withWebRoot("org/jboss/test/hello.xhtml").start(); } @After public void tearDown() throws Exception { this.environment.release(); }
Using in tests
After submit, it verifies that input element set new value to the session-scope bean ant that value was rendered back by outputText component:
@Test public void testHelloFacelets() throws Exception { HtmlPage page = environment.getPage("/hello.jsf"); HtmlForm htmlForm = page.getFormByName("helloForm"); HtmlInput input = htmlForm.getInputByName("helloForm:username"); input.setValueAttribute("foo"); HtmlElement submitElement = page.getElementById("helloForm:submit"); HtmlPage responsePage = submitElement.click(); HttpSession session = environment.getServer().getSession(false); HelloBean bean = (HelloBean) session.getAttribute("HelloBean"); assertEquals("foo", bean.getName()); Element span = responsePage.getElementById("responseform:userLabel"); assertEquals("foo", span.getTextContent().trim()); }
HtmlUnitRule
public class FacesTest { @Rule public HtmlUnitRule environment= HtmlUnitRule.create().withWebRoot("org/jboss/test/hello.xhtml");
Leave a Reply