Wednesday, 17 August 2011

Writing a web unit test using JWebUnit

Firstly, you will need to include the JWebUnit library in your Java project which is available to download (and is licensed under the GNU) here. You will also need the JUnit libraries as JWebUnit is built upon it which can be downloaded here (also under the GNU license).

Then in your test packages create the web test file. I recommend putting the web test file(s) in a web test package to separate them from any JUnit test files you may also have in your test packages.

package yourproject.webtest;

import net.sourceforge.jwebunit.junit.WebTestCase;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

public class WebUnitExample extends WebTestCase {

    @Before
    @Override
    public void setUp() throws Exception {
        super.setUp();
        // set up where JWebUnit should look
        setBaseUrl("http://localhost");
        beginAt("/webapp/thenameofyourproject/");
    }

    @After
    @Override
    public void tearDown() throws Exception {
        super.tearDown();
    }

    @Test
    public void testAFeatureOfYourProject() {
        System.out.println("Testing a feature of the project");
        // Add some method calls to the JWebUnit API here then call asserts to see if
        // the output is correct      
    }

}

How it works

As you can see this file is very incomplete and will not do anything at the moment but for this example that doesn't matter!

setUp and tearDown are important methods as you can set up what is needed before each test and obviously, 'tear down' i.e. remove those conditions after.

As for the tests themselves, JWebUnit has many methods that can be used to traverse the page (e.g. clickButton, clickLink) and methods to manipulate page elements (e.g. setTextField, selectOption). Just as in JUnit, asserts are used to check that things are how they should be. For a list of JWebUnit methods see their API listings.

1 comment:

  1. Hello, Can you give me an idea of how to test the Database Select query in Servlet using JwebUnit in Eclipse IDE.

    ReplyDelete