Skip to main content

Web testing BDD-style with JWebUnit and Easyb

Posted by johnsmart on August 16, 2009 at 8:19 PM PDT

Behaviour-driven development is a great way to design and build the web layers of your application. In this article, I look at how to use JWebUnit, a fast and light-weight web testing framework, with Easyb, a powerful Groovy-based BDD framework.

JWebUnit is a web testing framework built on HTMLUnit. It runs in memory, so it's fast. However, it also has an intuitive, high-level API, making it easy to use even if you have only an approximate idea of the exact HTML details of your application screens. A simple JWebUnit test case is shown here:


import net.sourceforge.jwebunit.junit.WebTestCase;
import net.sourceforge.jwebunit.junit.WebTester;

public class TestJWebUnitDepositStoryUI extends WebTestCase {

	public void setUp() {
		setBaseUrl("http://localhost:9090/ebank-web");
	}
	
	public void testDepositingCashShouldAddToBalance() {		
		beginAt("/");
		assertTextPresent("Current Balance: $0");
		setTextField("depositAmount","100");
		clickButtonWithText("deposit");
		assertTextPresent("Current Balance: $100");
	}
}

JWebUnit works fine like this, but we can still do better by adding a little BDD-flavoring to the mix. As it turns out, behaviour-driven development (or "behaviour-driven design") is a great way to model user interaction with your application. In BDD, you structure your requirements in a "given [some condition or state], when [some event occurs] then [we expect something else to happen]". For example, in an online banking application, one such requirement could be "Given that I am logged onto the bank web site and my bank account balance is $0, when I deposit $100, then the new balance should be $100."

Easyb is a behaviour-driven development (BDD) framework for Java and Groovy applications. It is based on Groovy, but uses a special DSL to express requirements and tests in BDD-style. Like many BDD frameworks, easyb lets you express your requirements (more precisely, your user's behaviour) in almost plain English, before filling in the details with test code. For example, here is a working Easyb test scenario describing how we might interact with our banking application:


scenario "Deposit cash via the web interface", {
    given "the application home page is displayed"
    and "the current balance is 0"
    when "I type \$100 in the 'deposit cash' field"
    and "I click on the 'deposit' button"
    then "the new balance should be \$100"
}

As far as Easyb is concerned, this is executable test code - however it won't do very much. When you run Easyb against a scenario like this one, it will be flagged as "pending implementation". So now let's see how we can implement this test using JWebUnit.

JWebUnit test cases need to extend the WebTestCase base class. This makes the framework hard to integrate with JUnit 4 or with pure Java-based BDD frameworks such as JBehave. However, Easyb is built on Groovy. With a little Groovy magic, we can embed a JWebUnit client inside our Easyb test scenarios. The only trick is that we still need to have a class that extends WebTestCase, as it is an Abstract class. We also need to initialize the internal 'tester' member variable with an instance of the WebTester class. A simple Groovy class like this will do the trick.


class DepositCashWebClient extends WebTestCase {

    public DepositCashWebClient() {
        tester = new WebTester();
    }
}

We also need to create a new instance of this class for each test case. We can do this using the Easyb "before_each" keyword, as shown here:


before_each "initialize a web client", {
  given "web client is up and running", {
      webClient = new DepositCashWebClient()
      webClient.setBaseUrl("http://localhost:9090/ebank")
  }
}

Our full Easyb test story looks like this:


import net.sourceforge.jwebunit.junit.WebTestCase;
import net.sourceforge.jwebunit.junit.WebTester;

class DepositCashWebClient extends WebTestCase {

    public DepositCashWebClient() {
        tester = new WebTester();
    }
};
    
before_each "initialize a web client", {
  given "web client is up and running", {
      webClient = new DepositCashWebClient()
      webClient.setBaseUrl("http://localhost:9090/ebank")
  }
}

scenario "Deposit cash via the web interface", {
    given "the application home page is displayed", {
      webClient.beginAt("/")
    }
    and "the current balance is 0", {
      webClient.assertTextPresent("Current Balance: \$0")
    }
    when "I type \$100 in the 'deposit cash' field", {
      webClient.setTextField("depositAmount","100")
    }
    and "I click on the 'deposit' button", {
      webClient.clickButtonWithText("deposit")
    } 
    then "the balance should be \$100", {
      webClient.assertTextPresent("Current Balance: \$100")
    }
}

And running these easyb scenarios will generate you a report that looks like this:

Picture 5.png

Although this seems longer than the Java version, it is arguably more readable, and reflects the intention of the code more accurately than the Java equivalent. The test report also makes it quite clear what requirements are being tested, in very readable terms. Writing the tests using a BDD approach also helps you keep a good perspective on how closely your application actually does what your users have asked for. Reports like the one above can also give users and testers a better understanding of what is being coded.

I will be talking about EasyB and BDD along with Lasse Koskela at Agile 2009 next week in Chicago, in a talk called Executable requirements: BDD with easyb and JDave. So, if you are interested to learn more about BDD, come along!

And if you want to learn more about Behaviour-Driven Development, web testing, Maven, and a whole lot of other useful tools and tricks, why not come along to a Java Power Tools bootcamp session - there are workshops coming up soon in Canberra, Sydney, Brisbane and Wellington.


"Probably the best training course I've been on."..."Not just how to write Java code but the 'business end' - how to build, test, deploy, manage and monitor"..."One of the best and most useful courses I have attended. And they didn't even try to sell me anything!" - There are still some places for the courses in Wellington, Canberra, Brisbane and Sydney - Get up to speed with the latest and coolest in Java tools and best practices! Sign up on the 2009 season of the Java Power Tools Bootcamps.

Comments

Yes the HTML reports are a great instant view, but without information from the run time output I found them lacking important info for debugging failures. We have altered our hudson config to have a post-build action of Archiving artifacts, then set the files to location of the report, i.e trunk/story-tests/target/report/*. Hudson now automagically presents the artifacts on the Build page, so we now keep a historic easyb html report and the console output!

Thanks. Have you tried the latest version of easyb for the HTML reports? They are much more readable and and more usable than the old ones. Unfortunately, easyb integrates poorly with CI tools like Hudson, as they only really understand JUnit-style test results. This shouldn't be a hard thing to do (just an XSL conversion, basically), but at the moment easyb doesn't have the option of producing JUnit-style results. For this, more Java-centric BDD tools like JBehave and JDave will work, but you loose the advantages of being able to work in Groovy (and being able to use JWebUnit). Thanks for your suggestion - I'll put your idea for a blog entry on my list and try to write something up on the topic.

Hi John, I have also starting to see the light with easyb but would like to have it work better with our continuous integration (hudson). I've found the output from easyb at the console level excessive, and yet the html report too sparse. Do you run easyb tests in a tool like hudson? If so I would love it if you were to post some examples around getting test output up to the hudson presentation level for reviewing not just the current build but previous one. Thanks for the Blog.