Showing posts with label JWebUnit. Show all posts
Showing posts with label JWebUnit. Show all posts

Monday, 27 February 2012

Run test via code

You can run your JUnit and JWebUnit tests from your own code. The class org.junit.runner.JUnitCore provides the method runClasses() which allows you to run one or several tests classes. As a return parameter you receive an object of the type org.junit.runner.Result. This object can be used to retrieve information about the tests.

import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

class RunTests {

    public static void main(String args[]) {
        Result result = JUnitCore.runClasses(TestClass.class);
        for (Failure failure : result.getFailures()) {
            System.out.println("FAIL!: " + failure.toString());
        }
    }
}

http://www.vogella.de/articles/JUnit/article.html

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.