Archive
Writing an Eclipse Plug-in (Part 14): Common Navigator: Refactoring the Children
Well, it is late on a Sunday afternoon and I really want to refactor the children of the navigator. There are about 22 warnings and I hate warnings (almost as much as I hate errors).
This is probably going to be a short posting with lots of code. Go with it.
What (are we doing?)
The tasks are as usual:
- Refactor common code
- Add annotations as needed
- Fix build path problems
- Externalize strings
Let’s refactor.
Refactor common code
The first thing we can safely say about the various node wrappers is that they all contain a reference to:
- Their parent
- Any children
- An image
That means that at the very least we can centralize the defintion of those three references. That means, using the refactor capability of Eclipse I pushed the following methods into a new parent class named CustomProjectElement:
- getText()
- getImage()
- getParent()
- getProject()
CustomProjectElement.java
package customnavigator.navigator;
import org.eclipse.core.resources.IProject;
import org.eclipse.swt.graphics.Image;
import customnavigator.Activator;
public abstract class CustomProjectElement implements ICustomProjectElement {
private Image _image;
private String _name;
private String _imagePath;
private ICustomProjectElement _parent;
private ICustomProjectElement[] _children;
public CustomProjectElement(ICustomProjectElement parent, String name, String imagePath) {
_parent = parent;
_name = name;
_imagePath = imagePath;
}
@Override
public String getText() {
return _name;
}
@Override
public Image getImage() {
if (_image == null) {
_image = Activator.getImage(_imagePath);
}
return _image;
}
@Override
public ICustomProjectElement getParent() {
return _parent;
}
@Override
public IProject getProject() {
return getParent().getProject();
}
@Override
public ICustomProjectElement[] getChildren() {
if (_children == null) {
_children = initializeChildren(getProject());
}
// else we have already initialized them
return _children;
}
@Override
public boolean hasChildren() {
if (_children == null) {
_children = initializeChildren(getProject());
}
// else we have already initialized them
return _children.length > 0;
}
protected abstract ICustomProjectElement[] initializeChildren(IProject project);
}
Centralizing the methods actually cut the warnings down to 12 and each class is significantly smaller having passed the trivial responsibility of the getter methods to the parent class.
Of course, now that we have refactored all that code we have to run some tests to show that the system still works, but we never wrote any tests for the wrapper classes.
What to do? What to do?
Oh, yeah. The wrapper classes come from the ContentProvider. We have plenty of tests for that one.
Run the customnavigator.test.
Oh oh! Three of the tests fail! Another perfect day! Time to debug. The first method to check: testGetChildrenForIWorkspaceRootWithOneCustomProject().
Ah! I needed to have another call to project.getName(). How interesting is that? The test code was wrong! I hate when that happens.
@Test
public void testGetChildrenForIWorkspaceRootWithOneCustomProject() throws CoreException {
IProject [] projects = new IProject[1];
IProject project = EasyMock.createStrictMock(IProject.class);
projects[0] = project;
IWorkspaceRoot workspaceRoot = EasyMock.createStrictMock(IWorkspaceRoot.class);
workspaceRoot.getProjects();
EasyMock.expectLastCall().andReturn(projects);
String projectName = "custom project"; //$NON-NLS-1$
project.getName();
EasyMock.expectLastCall().andReturn(projectName);
project.getNature(CUSTOMPLUGIN_PROJECT_NATURE);
EasyMock.expectLastCall().andReturn(EasyMock.createMock(IProjectNature.class));
project.getName();
EasyMock.expectLastCall().andReturn(projectName);
project.getName();
EasyMock.expectLastCall().andReturn(projectName);
EasyMock.replay(workspaceRoot, project);
Object [] actual = _contentProvider.getChildren(workspaceRoot);
Assert.assertNotNull(actual);
Assert.assertTrue(actual.length == 1);
Assert.assertEquals(project, ((CustomProjectParent)actual[0]).getProject());
EasyMock.verify(workspaceRoot, project);
}
Good. A green bar again.
Add annotations as needed
Already added as I refactored to a new parent class. Code below.
Fix build path problems
Open build.properties. There is a yellow mark next to bin.includes; press Ctrl+1 and select Add OSGI-INF/ to bin.includes Build Entry. Add it, please. That actually takes care of two warnings. Something about killing two warnings with one quick fix.
Open MANIFEST.MF. There is a yellow mark next to the Export-Package entry. Press Ctrl+1 and select Add Missing Packages. For some reason the Quick Fix did not work quite right so the Export-Package entry should look like this:
Export-Package: customnavigator.navigator, customnavigator.test, org.easymock, org.easymock.internal, org.easymock.internal.matchers
Externalize strings
Opening the Externalize Wizard on each of the node wrappers allowed me to externalize the image path strings. Now they are independent of the code in case we need to move them. Not likely, but what the hell.
The last 6 warnings need the following fixed:
- Potential null pointer access (which we can’t control since Eclipse calls the methods) – add @SuppressWarning(null) to ProjectNature
- Externalize a label in plugin.xml – Ctrl+1 at the offending line automatically takes care of that
- CoreException is not thrown in the methods we overrode in ProjectNature – add @SuppressWarnings(“unused”) to the three offending methods (two in CustomNature and one in CustomProjectNewWizard)
What Just Happened?
Lots of boring stuff was just done, but it was all necessary. The code is below.
Woo hoo. I think I will leave the cat alone in the box until next time.
Code
package customnavigator.navigator;
import org.eclipse.core.resources.IProject;
import org.eclipse.swt.graphics.Image;
import customnavigator.Activator;
public abstract class CustomProjectElement implements ICustomProjectElement {
private Image _image;
private String _name;
private String _imagePath;
private ICustomProjectElement _parent;
private ICustomProjectElement[] _children;
public CustomProjectElement(ICustomProjectElement parent, String name, String imagePath) {
_parent = parent;
_name = name;
_imagePath = imagePath;
}
@Override
public String getText() {
return _name;
}
@Override
public Image getImage() {
if (_image == null) {
_image = Activator.getImage(_imagePath);
}
return _image;
}
@Override
public ICustomProjectElement getParent() {
return _parent;
}
@Override
public IProject getProject() {
return getParent().getProject();
}
@Override
public ICustomProjectElement[] getChildren() {
if (_children == null) {
_children = initializeChildren(getProject());
}
// else we have already initialized them
return _children;
}
@Override
public boolean hasChildren() {
if (_children == null) {
_children = initializeChildren(getProject());
}
// else we have already initialized them
return _children.length > 0;
}
protected abstract ICustomProjectElement[] initializeChildren(IProject project);
}
/**
* Coder beware: this code is not warranted to do anything.
* Copyright Oct 17, 2009 Carlos Valcarcel
*/
package customnavigator.navigator;
import org.eclipse.core.resources.IProject;
/**
* @author carlos
*/
public class CustomProjectParent extends CustomProjectElement {
private IProject _project;
public CustomProjectParent(IProject iProject) {
super(null, iProject.getName(), Messages.CustomProjectParent_Project_Folder);
_project = iProject;
}
@Override
public IProject getProject() {
return _project;
}
@Override
protected ICustomProjectElement[] initializeChildren(IProject project) {
ICustomProjectElement[] children = {
new CustomProjectSchema(this),
new CustomProjectStoredProcedures(this)
};
return children;
}
}
/**
* Coder beware: this code is not warranted to do anything.
*
* Copyright Oct 18, 2009 Carlos Valcarcel
*/
package customnavigator.navigator;
import org.eclipse.core.resources.IProject;
/**
* @author carlos
*
*/
public class CustomProjectSchema extends CustomProjectElement {
public static final String NAME = "Schema"; //$NON-NLS-1$
public CustomProjectSchema(ICustomProjectElement parent) {
super(parent, NAME, Messages.CustomProjectSchema_Project_Schema);
}
@Override
protected ICustomProjectElement[] initializeChildren(IProject iProject) {
ICustomProjectElement[] children = new ICustomProjectElement [] {
new CustomProjectSchemaTables(this),
new CustomProjectSchemaViews(this),
new CustomProjectSchemaFilters(this)
};
return children;
}
}
/**
* Coder beware: this code is not warranted to do anything.
*
* Copyright Oct 18, 2009 Carlos Valcarcel
*/
package customnavigator.navigator;
import org.eclipse.core.resources.IProject;
/**
* @author carlos
*
*/
public class CustomProjectSchemaFilters extends CustomProjectElement {
public static final String NAME = "Filters"; //$NON-NLS-1$
public CustomProjectSchemaFilters(ICustomProjectElement parent) {
super(parent, NAME, Messages.CustomProjectSchemaFilters_Project_Schema_Filters);
}
/* (non-Javadoc)
* @see customnavigator.navigator.ICustomProjectElement#getChildren()
*/
@Override
protected ICustomProjectElement[] initializeChildren(IProject iProject) {
ICustomProjectElement[] children = new ICustomProjectElement [0];
return children;
}
}
/**
* Coder beware: this code is not warranted to do anything.
*
* Copyright Oct 18, 2009 Carlos Valcarcel
*/
package customnavigator.navigator;
import org.eclipse.core.resources.IProject;
/**
* @author carlos
*
*/
public class CustomProjectSchemaTables extends CustomProjectElement {
public static final String NAME = "Tables"; //$NON-NLS-1$
public CustomProjectSchemaTables(ICustomProjectElement parent) {
super(parent, NAME, Messages.CustomProjectSchemaTables_Project_Schema_Tables);
}
@Override
protected ICustomProjectElement[] initializeChildren(IProject iProject) {
ICustomProjectElement[] children = new ICustomProjectElement [0];
return children;
}
}
/**
* Coder beware: this code is not warranted to do anything.
*
* Copyright Oct 18, 2009 Carlos Valcarcel
*/
package customnavigator.navigator;
import org.eclipse.core.resources.IProject;
/**
* @author carlos
*
*/
public class CustomProjectSchemaViews extends CustomProjectElement {
public static final String NAME = "Views"; //$NON-NLS-1$
public CustomProjectSchemaViews(ICustomProjectElement parent) {
super(parent, NAME, Messages.CustomProjectSchemaViews_Project_Schema_Views);
}
@Override
protected ICustomProjectElement[] initializeChildren(IProject iProject) {
ICustomProjectElement[] children = new ICustomProjectElement [0];
return children;
}
}
/**
* Coder beware: this code is not warranted to do anything.
*
* Copyright Oct 18, 2009 Carlos Valcarcel
*/
package customnavigator.navigator;
import org.eclipse.core.resources.IProject;
/**
* @author carlos
*
*/
public class CustomProjectStoredProcedures extends CustomProjectElement {
public static final String NAME = "Stored Procedures"; //$NON-NLS-1$
public CustomProjectStoredProcedures(ICustomProjectElement parent) {
super(parent, NAME, Messages.CustomProjectStoredProcedures_Project_Stored_Procedures);
}
@Override
protected ICustomProjectElement[] initializeChildren(IProject iProject) {
ICustomProjectElement[] children = new ICustomProjectElement [0];
return children;
}
}
/**
* Coder beware: this code is not warranted to do anything.
* Copyright Oct 17, 2009 Carlos Valcarcel
*/
package customnavigator.navigator;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResourceChangeEvent;
import org.eclipse.core.resources.IResourceChangeListener;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.TreePath;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import customplugin.natures.ProjectNature;
/**
* @author carlos
*/
public class ContentProvider implements ITreeContentProvider, IResourceChangeListener {
private static final Object[] NO_CHILDREN = {};
private Map<String, Object> _wrapperCache = new HashMap<String, Object>();
private Viewer _viewer;
public ContentProvider() {
ResourcesPlugin.getWorkspace().addResourceChangeListener(this, IResourceChangeEvent.POST_CHANGE);
}
/*
* (non-Javadoc)
* @see
* org.eclipse.jface.viewers.ITreeContentProvider#getChildren(java.lang.Object)
*/
@Override
public Object[] getChildren(Object parentElement) {
Object[] children = null;
if (IWorkspaceRoot.class.isInstance(parentElement)) {
IProject[] projects = ((IWorkspaceRoot)parentElement).getProjects();
children = createCustomProjectParents(projects);
} else if (ICustomProjectElement.class.isInstance(parentElement)) {
children = ((ICustomProjectElement) parentElement).getChildren();
} else {
children = NO_CHILDREN;
}
return children;
}
/*
* (non-Javadoc)
* @see
* org.eclipse.jface.viewers.ITreeContentProvider#getParent(java.lang.Object)
*/
@SuppressWarnings("null")
@Override
public Object getParent(Object element) {
Object parent = null;
if (IProject.class.isInstance(element)) {
parent = ((IProject)element).getWorkspace().getRoot();
} else if (ICustomProjectElement.class.isInstance(element)) {
parent = ((ICustomProjectElement)element).getParent();
} // else parent = null if IWorkspaceRoot or anything else
return parent;
}
/*
* (non-Javadoc)
* @see
* org.eclipse.jface.viewers.ITreeContentProvider#hasChildren(java.lang.Object)
*/
@Override
public boolean hasChildren(Object element) {
boolean hasChildren = false;
if (IWorkspaceRoot.class.isInstance(element)) {
hasChildren = ((IWorkspaceRoot)element).getProjects().length > 0;
} else if (ICustomProjectElement.class.isInstance(element)) {
hasChildren = ((ICustomProjectElement)element).hasChildren();
}
// else it is not one of these so return false
return hasChildren;
}
/*
* (non-Javadoc)
* @see
* org.eclipse.jface.viewers.IStructuredContentProvider#getElements(java.lang.Object)
*/
@Override
public Object[] getElements(Object inputElement) {
// This is the same as getChildren() so we will call that instead
return getChildren(inputElement);
}
/*
* (non-Javadoc)
* @see org.eclipse.jface.viewers.IContentProvider#dispose()
*/
@Override
public void dispose() {
ResourcesPlugin.getWorkspace().removeResourceChangeListener(this);
}
/*
* (non-Javadoc)
* @see
* org.eclipse.jface.viewers.IContentProvider#inputChanged(org.eclipse.jface.viewers.Viewer, java.lang.Object, java.lang.Object)
*/
@Override
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
_viewer = viewer;
}
private int _count = 1;
@Override
public void resourceChanged(IResourceChangeEvent event) {
TreeViewer viewer = (TreeViewer) _viewer;
TreePath[] treePaths = viewer.getExpandedTreePaths();
viewer.refresh();
viewer.setExpandedTreePaths(treePaths);
System.out.println("ContentProvider.resourceChanged: completed refresh() and setExpandedXXX()"); //$NON-NLS-1$
}
private Object createCustomProjectParent(IProject parentElement) {
Object result = null;
try {
if (parentElement.getNature(ProjectNature.NATURE_ID) != null) {
result = new CustomProjectParent(parentElement);
}
} catch (CoreException e) {
// Go to the next IProject
}
return result;
}
private Object[] createCustomProjectParents(IProject[] projects) {
Object[] result = null;
List<Object> list = new ArrayList<Object>();
for (int i = 0; i < projects.length; i++) {
Object customProjectParent = _wrapperCache.get(projects[i].getName());
if (customProjectParent == null) {
customProjectParent = createCustomProjectParent(projects[i]);
if (customProjectParent != null) {
_wrapperCache.put(projects[i].getName(), customProjectParent);
}
}
if (customProjectParent != null) {
list.add(customProjectParent);
} // else ignore the project
}
result = new Object[list.size()];
list.toArray(result);
return result;
}
}
package customplugin.natures;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectNature;
import org.eclipse.core.runtime.CoreException;
public class ProjectNature implements IProjectNature {
public static final String NATURE_ID = "customplugin.projectNature"; //$NON-NLS-1$
@SuppressWarnings("unused")
@Override
public void configure() throws CoreException {
// TODO Auto-generated method stub
}
@SuppressWarnings("unused")
@Override
public void deconfigure() throws CoreException {
// TODO Auto-generated method stub
}
@Override
public IProject getProject() {
// TODO Auto-generated method stub
return null;
}
@Override
public void setProject(IProject project) {
// TODO Auto-generated method stub
}
}
package customplugin.wizards;
import java.net.URI;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExecutableExtension;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.dialogs.WizardNewProjectCreationPage;
import org.eclipse.ui.wizards.newresource.BasicNewProjectResourceWizard;
import customplugin.projects.CustomProjectSupport;
public class CustomProjectNewWizard extends Wizard implements INewWizard, IExecutableExtension {
private static final String WIZARD_NAME = "New Custom Plug-in Project"; //$NON-NLS-1$
private static final String PAGE_NAME = "Custom Plug-in Project Wizard"; //$NON-NLS-1$
private WizardNewProjectCreationPage _pageOne;
private IConfigurationElement _configurationElement;
public CustomProjectNewWizard() {
setWindowTitle(WIZARD_NAME);
}
@Override
public boolean performFinish() {
String name = _pageOne.getProjectName();
URI location = null;
if (!_pageOne.useDefaults()) {
location = _pageOne.getLocationURI();
} // else location == null
CustomProjectSupport.createProject(name, location);
BasicNewProjectResourceWizard.updatePerspective(_configurationElement);
return true;
}
@Override
public void addPages() {
super.addPages();
_pageOne = new WizardNewProjectCreationPage(PAGE_NAME);
_pageOne.setTitle(NewWizardMessages.CustomProjectNewWizard_Custom_Plugin_Project);
_pageOne.setDescription(NewWizardMessages.CustomProjectNewWizard_Create_something_custom);
addPage(_pageOne);
}
@Override
public void init(IWorkbench workbench, IStructuredSelection selection) {
// TODO Auto-generated method stub
}
@SuppressWarnings("unused")
@Override
public void setInitializationData(IConfigurationElement config, String propertyName, Object data) throws CoreException {
_configurationElement = config;
}
}
plugin.xml
<?xml version="1.0" encoding="UTF-8"?>
<?eclipse version="3.2"?>
<plugin>
<extension
point="org.eclipse.ui.newWizards">
<category
id="customplugin.category.wizards"
name="%category.name">
</category>
<wizard
category="customplugin.category.wizards"
class="customplugin.wizards.CustomProjectNewWizard"
finalPerspective="customplugin.perspective"
icon="icons/project-folder.png"
id="customplugin.wizard.new.custom"
name="%wizard.name">
</wizard>
<wizard
category="customplugin.category.wizards"
class="customplugin.wizards.CustomProjectNewSchemaFile"
descriptionImage="icons/schema-file_32x32.png"
icon="icons/schema-file_16x16.png"
id="customplugin.wizard.file.schema"
name="%wizard.name.schema">
</wizard>
<wizard
category="customplugin.category.wizards"
class="customplugin.wizards.CustomProjectNewDeploymentFile"
descriptionImage="icons/deployment-file_32x32.png"
icon="icons/deployment-file_16x16.png"
id="customplugin.wizard.file.deployment"
name="%wizard.name.deployment">
</wizard>
</extension>
<extension
point="org.eclipse.ui.perspectives">
<perspective
class="customplugin.perspectives.Perspective"
icon="icons/perspective.png"
id="customplugin.perspective"
name="%perspective.name">
</perspective>
</extension>
<extension
point="org.eclipse.ui.perspectiveExtensions">
<perspectiveExtension
targetID="customplugin.perspective">
<view
id="customnavigator.navigator"
minimized="false"
ratio=".25"
relationship="left"
relative="org.eclipse.ui.editorss">
</view>
</perspectiveExtension>
</extension>
<extension
id="customplugin.projectNature"
point="org.eclipse.core.resources.natures">
<runtime>
<run
class="customplugin.natures.ProjectNature">
</run>
</runtime>
</extension>
<extension
point="org.eclipse.ui.ide.projectNatureImages">
<image
icon="icons/project-folder.png"
id="customplugin.natureImage"
natureId="customplugin.projectNature">
</image>
</extension>
<extension
id="customplugin.contenttype"
point="org.eclipse.core.contenttype.contentTypes">
<content-type
base-type="org.eclipse.core.runtime.xml"
file-extensions="xml"
id="customplugin.contenttype.schema"
name="%content-type.name.schema"
priority="normal">
<describer
class="org.eclipse.core.runtime.content.XMLRootElementContentDescriber2">
<parameter
name="element"
value="hc-schema">
</parameter>
</describer>
</content-type>
<content-type
base-type="org.eclipse.core.runtime.xml"
file-extensions="xml"
id="customplugin.contenttype.deployment"
name="%content-type.name.deployment"
priority="normal">
<describer
class="org.eclipse.core.runtime.content.XMLRootElementContentDescriber2">
<parameter
name="element"
value="hc-deployment">
</parameter>
</describer>
</content-type>
</extension>
<extension
point="org.eclipse.ui.menus">
<menuContribution
locationURI="popup:org.eclipse.ui.popup.any?after=additions">
<menu
label="%menu.label">
<visibleWhen
checkEnabled="true">
</visibleWhen>
</menu>
</menuContribution>
</extension>
</plugin>
And Now By Popular Demand: jWebUnit
In the land of TDD things start pretty raw (plain vanilla JUnit) and slowly work their way out. While there are all sorts of areas to test (databases, web services, servlets, EJBs, POJOs and others) the fact is you not only have to be conscious of your testing, but you have to also decide how much testing to do. During the implementation of web applications what you find out is that your tests can do at least one of two things:
- flow testing
- integration testing
The thing is you don’t want any one test to do both. You should have one test for flow (unit) testing and another for integration testing.
Are there other test types? Of course (you just have to read JUnit Recipes to figure that out). Being the lazy guy that I am I really only perform functional and integration tests when I write my own code and rely on the customer to decide how far down the rabbit hole they want to go. How can you help them decide how much testing to do? Ask a simple question: how much would they lose if something went wrong? This is a question of risk tolerance. Software responsible for life and death should be tested until the cows come home. Software that is responsible for making/saving money should be tested to the customers limit of legal liability; after that test to what they can afford, but at least now you have a baseline.
But I digress. It must be the squirrels.
There are a lot of frameworks for web app testing and I have arbitrarily chosen jWebUnit as the winner because I am boring and stuck in the past thoughtful and forward-looking and I have just not had time to look at all of the available choices some of which are:
[I remember looking at FitNesse and Selenium and even bought a book on FitNesse, but never got so far as to actually implement anything with it. My loss. It looks really good.]
There are so many things to say about what you should be thinking and how you should be thinking in regards to your tests. My recommendation is that you should use your use cases to guide your integration testing (you are writing use cases, aren’t you?) and just get to work. If you want philosophical guidance (and I am never short of that) you should read as much as you can about TDD and testing at all of the various levels. For example:
- TDD (unit testing in general): http://www.agiledata.org/essays/tdd.html
- JUnit (POJO testing): http://junit.sourceforge.net/doc/cookbook/cookbook.htm
- JUnit in Eclipse: http://www.eclipsekickstart.com/chapters/EclipseKickStart-ch06.pdf (yes, shameless plug)
- DBUnit (database testing): http://www.dbunit.org/howto.html
- jWebUnit (web framework testing)
[Just as an aside: I love Spring. TDD is so easy with Spring. You test every level of your application (db, POJOs, messaging, web pages) as if they were all POJOs…because they are. If you can use Spring to develop your apps, web or otherwise, please use it. I can’t imagine developing an application without it.]
Enough mayonnaise. What are we doing? How are we doing it? Why did we do it that way?
What (are we doing?)
The Use Case:
Actor: A Visitor (not like from V, but they could use this too)
Scenario 1:
1a: The Visitor, wanting to register for a special Hidden Clause prize, is on the registration page. The registration form has the following fields:
- Name (no more than 30 characters, no numbers)
- Password (hidden)
If they user does not enter information in either or both fields display the form again and ask them to enter valid information.
1b: When the visitor has submitted the registration page they will be asked to confirm their information.
1c. When they confirm that the information we have is correct a Success page will reassure them that they will be receiving their HC prize any day now.
Scenario 2:
2a. As above in 1a.
2b. When the visitor has submitted the registration page they will be asked to confirm their information. If the information is incorrect open the registration form again with their current information.
2c. As above in 1c.
Scenario 3:
3a. As above in 1a.
3b. As above in 1b.
3c. The registration process failed due to a system failure. Apologize to the user and ask them to try again later or call in for their prize.
The tests:
- Scenario 1
- Good scenario
- Check title for login page
- Fill in the two fields with valid information
- Submit login page
- Check title for confirmation
- Confirm that the content we entered was accepted
- Submit confirmation page
- Check title for success page
- Confirm success message
- Error scenario 1 – required fields empty
- Go to login page
- Submit login page without filling in the fields
- Check login page for error message
- Error scenario 2 – required content is invalid
- Go to login page
- Fill in the two fields with invalid information
- Submit login information
- Check login page for error message
- Error scenario 3 – unknown error occurred on submit
- Go to login page
- Fill in the two fields with valid information
- Submit login information
- Check login page for error message
- Good scenario
- Scenario 2
- Good scenario
- Check title for login page
- Fill in the two fields with valid information
- Submit login page
- Check title for confirmation page
- Confirm that the content we entered was accepted
- Cancel confirmation page
- Confirm return to login page
- Confirm fields are filled in
- Error scenario
- None
- Good scenario
- Scenario 3
- Good scenario
- Go to login page
- Fill in the two fields with valid information
- Submit login page
- Check title for confirmation page
- Submit confirmation page
- Confirm error page is display with associated message
- Error scenario
- None
- Good scenario
Things we are not doing:
- Testing field validation
- Testing database behavior
It is not that we don’t care (well, I don’t but…), but rather that the code for that behavior should already have been tested. If we are doing integration testing we are just guaranteeing that the behavior we expect actually occurs. If the various tests have been done then we can be sure that things should work. However, things can still fail which is why running integration tests is so important.
The tests above are just what I came up with off the top of my head. Never be afraid to add more tests to your test suite, but remember: don’t test things you don’t have to.
How (are we doing it?)
Software Requirements
- Eclipse 3.5 (so I can leverage the JEE functionality)
- JUnit 4 (part of Eclipse)
- jWebUnit 2.2
- Tomcat 6.0
- Create a Java Project and name if jWebUnit-HiddenClausePrizeTest
- Add jWebUnit to the project through the project Preferences window
- jwebunit-core-2.2.jar
- jwebunit-htmlunit-plugin-2.2.jar
- All of the JAR files under $JWEBUNIT/lib
- Create a JUnit Test Case
- JUnit 4
- Package: com.hiddenclause.jwebunit.example
- Name: UseCaseRegistrationTest
- Scenario 1
- Implement testScenario1EverythingWorks()
- Implement testScenario1EmptyInputFields()
- Implement testScenario1InvalidNameInputNumeric()
- Implement testScenario1InvalidNameInputLength()
- Implement testScenario1InvalidPasswordInputNumeric()
- Implement testScenario1InvalidPasswordInputLength()
- Implement testScenario1UnknownError()
- Scenario 2
- Implement testScenario2UserReEntersRegistrationInformation()
- Scenario 3
- Implement testScenario3SystemErrorOnConfirm()
I did not list the code above as it is all duplicated below.
Why (did we do it that way?)
With any luck you have already created the Java project with JUnit 4 and the various jWebUnit JAR files. If not, rewind, perform the first few steps of the How section and come back.
In TDD you are supposed to:
- Write a test and watch it fail
- Write the code to make the test pass and watch it pass
- Refactor
In short: lather, rinse, repeat. As you write the tests the implementation code comes to life, you finish your project early and your manager showers you with riches and accolades and all will be right with the world.
Good luck with that last part.
So let’s test Scenario 1 of the use case.
Implement testScenario1EverythingWorks()
We start by writing a minimal setUp() method and a call to WebTester.beginAt() in testScenario1EverythingWorks().
UseCaseRegistrationTest.java
public class UseCaseRegistrationTest {
private WebTester _webTester;
@Before
public void setUp() {
_webTester = new WebTester();
_webTester.setTestingEngineKey(TestingEngineRegistry.TESTING_ENGINE_HTMLUNIT);
_webTester.setBaseUrl("http://localhost:8080/hiddenclause"); //$NON-NLS-1$
}
@Test
public void testScenario1EverythingWorks() {
_webTester.beginAt("/login.jsp");
}
}
Run the above and watch it fail. Excellent! Not only does login.jsp not exist neither does the web context hiddenclause. Time to write the code that passes.
- Create a Dynamic Web Project and name it (wait for it) hiddenclause
- Assign your Tomcat 6.0 installation as the Target Runtime
- Create a JSP page and name it login.jsp
- Right click on hiddenclause –> WebContent –> login.jsp –> Run on Server and click Finish
The Eclipse web browser should open on an empty page. Perfect. Run the jWebUnit test again. The test passes. What? You call that a test? Well, yes; anytime you find bad behavior you are testing your expectations of the system; something goes wrong and you do something to fix it. This is all part of the interactivity of test-driven development. Embrace it.
Quick review: what are we trying to test in the flow for scenario 1:
- Check title for login page
- Fill in the two fields with valid information
- Submit login page
- Check title for confirmation page
- Confirm that the content we entered was accepted
- Submit confirmation page
- Check title for success page
- Confirm success message
Let’s check for the title:
UseCaseRegistrationTest.java
@Test
public void testScenario1EverythingWorks() {
_webTester.beginAt("/login.jsp");
_webTester.assertTitleEquals("Welcome! Register here!");
}
Run the test. Hmm. Lots of red. Hmm. The title doesn’t appear to be in login.jsp. I guess we should put it in.
login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Welcome! Register here!</title>
</head>
<body>
</body>
</html>
Run the test. Should pass.
So the pattern will be: add code to the test until we hit an assertion. At that point:
- Run the test
- See the assert fail
- Update the JSP
- Run the test again
- See the JSP pass
What’s next:
- Fill in the two fields with valid information
- Submit login page
- Check title for confirmation page
UseCaseRegistrationTest.java
@Test
public void testScenario1EverythingWorks() {
_webTester.beginAt("/login.jsp");
_webTester.assertTitleEquals("Welcome! Register here!");
String username = "Paul Revere";
String password = "OneIfByLand";
_webTester.setTextField("username", username);
_webTester.setTextField("password", password);
_webTester.submit();
_webTester.assertTitleEquals("Confirm Registration Information");
}
Run the test. To fix the failure update login.jsp with:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Welcome! Register here!</title>
</head>
<body>
<form action="confirmation.jsp">
<input name="username">
<input name="password" type="hidden">
<input type="submit" value="Submit">
</form>
</body>
</html>
Create confirmation.jsp and give it the proper title based on the test:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Confirm Registration Information</title>
</head>
<body>
</body>
</html>
Run the test; you should pass.
What’s next:
- Confirm that the content we entered was accepted
- Submit confirmation page
- Check title for success page
- Confirm success message
UseCaseRegistrationTest.java
@Test
public void testScenario1EverythingWorks() {
...
_webTester.assertTitleEquals("Confirm Registration Information");
_webTester.assertTextPresent(username);
_webTester.assertTextPresent(password);
_webTester.submit();
_webTester.assertTitleEquals("Success!");
_webTester.assertTextPresent("Thanks for registering!");
}
Run the test. Fix the failure by updating confirmation.jsp with:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Confirm Registration Information</title>
</head>
<body>
Name: <%=request.getParameter("username") %>
Password: <%=request.getParameter("password") %>
<form action="success.jsp">
<input type="submit" value="Submit">
</form>
</body>
</html>
Also create success.jsp and change the title:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Success!</title>
</head>
<body>
Thanks for registering!
</body>
</html>
Run the test; you should pass.
I hope you have been finding the jWebUnit code interesting. It is almost script-like. I find that rather than write down the flow on a white board I can just about type it directly into the test and add the calls to the proper jWebUnit API. Very very cool (that’s two verys).
So let’s agree on a process: from here on down I will list the scenario, you will enter the test code, you will execute the test code, you will update the JSP and/or HTML, and you will run the test again. Agreed?
Okay. Let’s go.
Implement testScenario1EmptyInputFields()
Error scenario 1
- Go to login page
- Submit login page without filling in the fields
- Check login page for error message
UseCaseRegistrationTest.java
@Test
public void testScenario1EmptyInputFields() {
_webTester.beginAt("/login.jsp");
_webTester.submit();
_webTester.assertTitleEquals("Welcome! Register here!");
_webTester.assertTextPresent("All fields are required! Try again! Don't make me go back there!");
}
login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Welcome! Register here!</title>
</head>
<body>
<%
String msg = null;
String submit = request.getParameter("submit");
if (submit != null && submit.equals("Submit")) {
String username = request.getParameter("username");
String password = request.getParameter("password");
if (username == null
|| username.trim().length() == 0
|| password == null
|| password.trim().length() == 0) {
msg = "All fields are required! Try again! Don't make me go back there!";
}
if (msg == null) {
request.getRequestDispatcher("confirmation.jsp").forward(request, response);
} else {
%>
<span style="color: red;"><%=msg %></span>
<%
}
}
%>
<form action="login.jsp">
<input name="username">
<input name="password" type="hidden">
<input type="submit" value="Submit" name="submit">
</form>
</body>
</html>
Implement testScenario1InvalidNameInputNumeric()
Error scenario 2
- Go to login page
- Fill in the name field with invalid information
- Submit page login page
- Check login page for error message
UseCaseRegistrationTest.java
@Test
public void testScenario1InvalidNameInputNumeric() {
_webTester.beginAt("/login.jsp");
_webTester.setTextField("username", "thx1138");
_webTester.setTextField("password", "hi");
_webTester.submit();
_webTester.assertTitleEquals("Welcome! Register here!");
_webTester.assertTextPresent("Yo! The username field can only contain letters!");
}
login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@page import="java.util.regex.Pattern"%>
<%@page import="java.util.regex.Matcher"%>
<%!
private Pattern _pattern = Pattern.compile("[0-9]");
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Welcome! Register here!</title>
</head>
<body>
<%
String msg = null;
String submit = request.getParameter("submit");
if (submit != null && submit.equals("Submit")) {
String username = request.getParameter("username");
String password = request.getParameter("password");
if (username == null
|| username.trim().length() == 0
|| password == null
|| password.trim().length() == 0) {
msg = "All fields are required! Try again! Don't make me go back there!";
} else {
Matcher matcher = _pattern.matcher(username);
if (matcher.find()) {
msg = "Yo! The username field can only contain letters!";
}
}
if (msg == null) {
request.getRequestDispatcher("confirmation.jsp").forward(request, response);
} else {
%>
<span style="color: red;"><%=msg %></span>
<%
}
}
%>
<form action="login.jsp">
<input name="username">
<input name="password" type="hidden">
<input type="submit" value="Submit" name="submit">
</form>
</body>
</html>
Implement testScenario1InvalidNameInputLength()
UseCaseRegistrationTest.java
UseCaseRegistrationTest.java
@Test
public void testScenario1InvalidNameInputLength() {
_webTester.beginAt("/login.jsp");
_webTester.setTextField("username", "abcdefghijklmnopqrstuvwxyzABCDE");
_webTester.setTextField("password", "hi");
_webTester.submit();
_webTester.assertTitleEquals("Welcome! Register here!");
_webTester.assertTextPresent("Yo! The username can only be 30 letters or less!");
}
login.jsp
<%
String msg = null;
String submit = request.getParameter("submit");
if (submit != null && submit.equals("Submit")) {
String username = request.getParameter("username");
String password = request.getParameter("password");
if (username == null
|| username.trim().length() == 0
|| password == null
|| password.trim().length() == 0) {
msg = "All fields are required! Try again! Don't make me go back there!";
} else {
Matcher matcher = _pattern.matcher(username);
if (matcher.find()) {
msg = "Yo! The username can only contain letters!";
}
if (username.trim().length() > 30) {
msg = "Yo! The username can only be 30 letters or less!";
}
}
if (msg == null) {
request.getRequestDispatcher("confirmation.jsp").forward(request, response);
} else {
%>
<span style="color: red;"><%=msg %></span>
<%
}
}
%>
Implement testScenario1InvalidPasswordInputNumeric()
Error scenario 2
- Go to login page
- Fill in the password fields with invalid information
- Submit login page
- Check login page for error message
UseCaseRegistrationTest.java
/*
* The code for these methods is the same. Refactored them.
*/
@Test
public void testScenario1InvalidNameInputNumeric() {
assertNumericField("thx1138", "hi", "Yo! The username can only contain letters!");
}
@Test
public void testScenario1InvalidPasswordInputNumeric() {
assertNumericField("Paul Revere", "thx1138", "Yo! The password can only contain letters!");
}
private void assertNumericField(String username, String password,
String errMsg) {
_webTester.beginAt("/login.jsp");
_webTester.setTextField("username", username);
_webTester.setTextField("password", password);
_webTester.submit();
_webTester.assertTitleEquals("Welcome! Register here!");
_webTester.assertTextPresent(errMsg);
}
login.jsp
<%
String msg = null;
String submit = request.getParameter("submit");
if (submit != null && submit.equals("Submit")) {
String username = request.getParameter("username");
String password = request.getParameter("password");
if (username == null
|| username.trim().length() == 0
|| password == null
|| password.trim().length() == 0) {
msg = "All fields are required! Try again! Don't make me go back there!";
} else {
Matcher matcher = _pattern.matcher(username);
if (matcher.find()) {
msg = "Yo! The username can only contain letters!";
} else if (username.trim().length() > 30) {
msg = "Yo! The username can only be 30 letters or less!";
} else {
matcher = _pattern.matcher(password);
if (matcher.find()) {
msg = "Yo! The password can only contain letters!";
}
}
}
if (msg == null) {
request.getRequestDispatcher("confirmation.jsp").forward(request, response);
} else {
%>
<span style="color: red;"><%=msg %></span>
<%
}
}
%>
Implement testScenario1InvalidPasswordInputLength()
UseCaseRegistrationTest.java
/*
* The code for these methods is the same. Refactored them.
*/
@Test
public void testScenario1InvalidNameInputLength() {
assertFieldLengthErrorFound("abcdefghijklmnopqrstuvwxyzABCDE", "hi", "Yo! The username can only be 30 letters or less!");
}
@Test
public void testScenario1InvalidPasswordInputLength() {
assertFieldLengthErrorFound("Paul Revere", "abcdefghijklmnopqrstuvwxyzABCDE", "Yo! The password can only be 30 letters or less!");
}
private void assertFieldLengthErrorFound(String username, String password,
String errMsg) {
_webTester.beginAt("/login.jsp");
_webTester.setTextField("username", username);
_webTester.setTextField("password", password);
_webTester.submit();
_webTester.assertTitleEquals("Welcome! Register here!");
_webTester.assertTextPresent(errMsg);
}
login.jsp
<%
String msg = null;
String submit = request.getParameter("submit");
if (submit != null && submit.equals("Submit")) {
String username = request.getParameter("username");
String password = request.getParameter("password");
if (username == null
|| username.trim().length() == 0
|| password == null
|| password.trim().length() == 0) {
msg = "All fields are required! Try again! Don't make me go back there!";
} else {
Matcher matcher = _pattern.matcher(username);
if (matcher.find()) {
msg = "Yo! The username can only contain letters!";
} else if (username.trim().length() > 30) {
msg = "Yo! The username can only be 30 letters or less!";
} else {
matcher = _pattern.matcher(password);
if (matcher.find()) {
msg = "Yo! The password can only contain letters!";
} else if (password.trim().length() > 30) {
msg = "Yo! The password can only be 30 letters or less!";
}
}
}
if (msg == null) {
request.getRequestDispatcher("confirmation.jsp").forward(request, response);
} else {
%>
<span style="color: red;"><%=msg %></span>
<%
}
}
%>
Implement testScenario1UnknownErrorOnSubmit()
Scenario 1 – Unknown error on submit
- Go to login page
- Fill in the two fields with valid information
- Submit login page
- Check login page for error message
UseCaseRegistrationTest.java
@Test
public void testScenario1UnknownErrorOnSubmit() {
_webTester.beginAt("/login.jsp");
String username = "Force an error";
String password = "VeryBad";
_webTester.setTextField("username", username);
_webTester.setTextField("password", password);
_webTester.submit();
_webTester.assertTitleEquals("Welcome! Register here!");
_webTester.assertTextPresent("I'm sorry, but we seem to have encountered an error. Please try again later or contact Hidden Clause customer support.");
}
login.jsp
<%
String msg = null;
String submit = request.getParameter("submit");
String username = request.getParameter("username");
String password = request.getParameter("password");
if (submit != null && submit.equals("Submit")) {
if (username == null
|| username.trim().length() == 0
|| password == null
|| password.trim().length() == 0) {
msg = "All fields are required! Try again! Don't make me go back there!";
} else if (username.equals("Force an error")) {
// This else if would normally not be here. This is here to force an error
// so we can check if our code can handle it.
msg = "I'm sorry, but we seem to have encountered an error. Please try again later or contact Hidden Clause customer support.";
} else {
Matcher matcher = _pattern.matcher(username);
if (matcher.find()) {
msg = "Yo! The username can only contain letters!";
} else if (username.trim().length() > 30) {
msg = "Yo! The username can only be 30 letters or less!";
} else {
matcher = _pattern.matcher(password);
if (matcher.find()) {
msg = "Yo! The password can only contain letters!";
} else if (password.trim().length() > 30) {
msg = "Yo! The password can only be 30 letters or less!";
}
}
}
if (msg == null) {
request.getRequestDispatcher("confirmation.jsp").forward(request, response);
} else {
%>
<span style="color: red;"><%=msg %></span>
<%
}
}
%>
Implement testScenario2UserReEntersRegistrationInformation()
Scenario 2
Visitor changes registration information
- Go to login page
- Fill in the two fields with valid information
- Submit login page
- Check title for confirmation page
- Cancel confirmation page
- Confirm return to login page
- Confirm fields are filled in
UseCaseRegistrationTest.java
@Test
public void testScenario2UserReEntersRegistrationInformation() {
_webTester.beginAt("/login.jsp");
String username = "Paul Revere";
String password = "OneIfByLand";
_webTester.setTextField("username", username);
_webTester.setTextField("password", password);
_webTester.submit();
_webTester.assertTitleEquals("Confirm Registration Information");
_webTester.submit("edit");
_webTester.assertTitleEquals("Welcome! Register here!");
_webTester.assertTextFieldEquals("username", username);
_webTester.assertTextFieldEquals("password", password);
}
login.jsp
<body>
<%
String msg = null;
String submit = request.getParameter("submit");
String username = request.getParameter("username");
String password = request.getParameter("password");
if (submit != null && submit.equals("Submit")) {
if (username == null
|| username.trim().length() == 0
|| password == null
|| password.trim().length() == 0) {
msg = "All fields are required! Try again! Don't make me go back there!";
} else if (username.equals("Force an error")) {
msg = "I'm sorry, but we seem to have encountered an error. Please try again later or contact Hidden Clause customer support.";
} else {
Matcher matcher = _pattern.matcher(username);
if (matcher.find()) {
msg = "Yo! The username can only contain letters!";
} else if (username.trim().length() > 30) {
msg = "Yo! The username can only be 30 letters or less!";
} else {
matcher = _pattern.matcher(password);
if (matcher.find()) {
msg = "Yo! The password can only contain letters!";
} else if (password.trim().length() > 30) {
msg = "Yo! The password can only be 30 letters or less!";
}
}
}
if (msg == null) {
request.getRequestDispatcher("confirmation.jsp").forward(request, response);
} else {
%>
<span style="color: red;"><%=msg %></span>
<%
}
}
%>
<form action="login.jsp">
<input name="username" value='<%=username != null ? username : "" %>'>
<input name="password" type="hidden" value='<%= password != null ? password : "" %>'>
<input type="submit" value="Submit" name="submit">
</form>
</body>
confirmation.jsp
<body>
<%
String username = request.getParameter("username");
String password = request.getParameter("password");
%>
Name: <%= username %>
Password: <%= password %>
<form action="success.jsp">
<input type="submit" value="Submit">
</form>
<form action="login.jsp?">
<input type="hidden" name="username" value="<%=username %>">
<input type="hidden" name="password" value="<%=password %>">
<input type="submit" name="edit" value="Edit">
</form>
</body>
Implement testScenario3SystemErrorOnConfirm()
Scenario on system error
- Go to login page
- Fill in the two fields with valid information
- Submit login page
- Check title for confirmation page
- Submit confirmation page
- Confirm error page is display with associated message
UseCaseRegistrationTest.java
@Test
public void testScenario3SystemErrorOnConfirm() {
_webTester.beginAt("/login.jsp");
String username = "Confirmation error";
String password = "OneIfByLand";
_webTester.setTextField("username", username);
_webTester.setTextField("password", password);
_webTester.submit();
_webTester.assertTitleEquals("Confirm Registration Information");
_webTester.submit();
assertLoginPageWithErrorMessage("I'm sorry, but we seem to have encountered an error. Please try again later or contact Hidden Clause customer support.");
}
login.jsp
<%
String msg = null;
String submit = request.getParameter("submit");
String username = request.getParameter("username");
String password = request.getParameter("password");
if (submit != null && submit.equals("Submit")) {
if (username == null
|| username.trim().length() == 0
|| password == null
|| password.trim().length() == 0) {
msg = "All fields are required! Try again! Don't make me go back there!";
} else if (username.equals("Force an error")) {
msg = "I'm sorry, but we seem to have encountered an error. Please try again later or contact Hidden Clause customer support.";
} else {
Matcher matcher = _pattern.matcher(username);
if (matcher.find()) {
msg = "Yo! The username can only contain letters!";
} else if (username.trim().length() > 30) {
msg = "Yo! The username can only be 30 letters or less!";
} else {
matcher = _pattern.matcher(password);
if (matcher.find()) {
msg = "Yo! The password can only contain letters!";
} else if (password.trim().length() > 30) {
msg = "Yo! The password can only be 30 letters or less!";
}
}
}
if (msg == null) {
request.getRequestDispatcher("confirmation.jsp").forward(request, response);
} else {
%>
<span style="color: red;"><%=msg %></span>
<%
}
}
%>
confirmation.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Confirm Registration Information</title>
</head>
<body>
<%
String username = request.getParameter("username");
String password = request.getParameter("password");
%>
Name: <%= username %>
Password: <%= password %>
<form action="success.jsp">
<input type="hidden" name="username" value="<%=username %>">
<input type="hidden" name="password" value="<%=password %>">
<input type="submit" value="Submit">
</form>
<form action="login.jsp?">
<input type="hidden" name="username" value="<%=username %>">
<input type="hidden" name="password" value="<%=password %>">
<input type="submit" name="edit" value="Edit">
</form>
</body>
</html>
success.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%
String username = request.getParameter("username");
if (username.equals("Confirmation error")) {
request.getRequestDispatcher("login.jsp?username=Force%20an%20error&submit=Submit").forward(request, response);
}
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Success!</title>
</head>
<body>
</body>
</html>
Notice how things that we tested previously don’t get tested again (empty input fields, invalid input). Just because an error can happen across scenarios doesn’t mean we have to test it in each scenario.
jWebUnit has a great API. It mixes a little testing (assertTitleEquals()) with a little flow (clickLink()).
What Just Happened?
I know, I know! The actual HTML pages are ugly, ugly, ugly! You can’t even see the two input fields side by side to see if they are really there; but they are really there because the tests passed.
That’s not a problem! The only thing we care about is the flow. We were able to prove that we can go from page to page based on the decisions made by the user or caused by the system. Let some high-priced GUI person step in and design some kick-ass screen that will make Minority Report envious.
Otherwise, wasn’t that interesting? That is quite a bit of code to test our flow and doesn’t really take into account all sorts of other scenarios. But that’s okay! Really. Remember that the pages above are fake…meaning that you would not normally have hard-coded Java in a JSP anyway. I used it just to get my tests up and running; normally you would have JSP tags and/or calls to servlet/Struts/WebWork/Tapestry code that would do all the real work (like validating the input).
What web testing framework are you using? Care to share?
The full code for this is below because I am sure that I left something out somewhere. Remember: not only did I develop this iteratively, I wrote it that way too. Not always a recipe for success.
Thanks to Ken Kranz for suggesting this topic.
Questions
I’m confused! If we are not supposed to test functionality that has been tested previously then why did we test input handling (input length and letters-only)?
Great question! By rights if you are using a web framework like Struts or WebWorks you should already have tests in place that would check for things like missing or incorrect values. In a truly secure application you would have JavaScript doing validation on the client-side and then do the exact same checks again on the server-side just to be sure that someone isn’t trying to get around your security. If you use a web framework and you don’t want to have duplicate validation then, no, you would not have tested input validation within jWebUnit.
From where did Molotov cocktails get their name?
They are called Molotov cocktails after Vyacheslav Molotov, the Commissar for Foreign Affairs of the Soviet Union, during World War II. Wikipedia has this to say about Molotov cocktails:
During the [World War II] Winter War, the Soviet air force made extensive use of incendiaries and cluster bombs against Finnish troops and fortifications. When Soviet People’s Commissar for Foreign Affairs Vyacheslav Molotov claimed in radio broadcasts that the Soviet Union was not dropping bombs but rather delivering food to the starving Finns, the Finns started to call the air bombs Molotov bread baskets. Soon they responded by attacking advancing tanks with “Molotov cocktails” which were “a drink to go with the food”.
Can’t make this stuff up.
[What? You were expecting questions related to jWebUnit? Oh, c’mon!]
References
Test Web applications with HttpUnit is a great article on unit testing your web application and, even though it was written in 2004 (there were people back then?) does a great job of discussing the sorts of architectural and philosophical things you should consider as you add (more) testing to your process.
Tools For Unit Testing Java Web Applications
Continuous Integration
Team City
Code
UseCaseRegistrationTest.java
/**
* Coder beware: this code is not warranted to do anything.
*
* Copyright Dec 12, 2009 Carlos Valcarcel
*/
package com.hiddenclause.jwebunit.example;
import net.sourceforge.jwebunit.junit.WebTester;
import net.sourceforge.jwebunit.util.TestingEngineRegistry;
import org.junit.Before;
import org.junit.Test;
/**
* @author carlos
*
*/
public class UseCaseRegistrationTest {
private WebTester _webTester;
@Before
public void setUp() {
_webTester = new WebTester();
_webTester.setTestingEngineKey(TestingEngineRegistry.TESTING_ENGINE_HTMLUNIT);
_webTester.setBaseUrl("http://localhost:8080/hiddenclause"); //$NON-NLS-1$
}
@Test
public void testScenario1EverythingWorks() {
_webTester.beginAt("/login.jsp");
_webTester.assertTitleEquals("Welcome! Register here!");
String username = "Paul Revere";
String password = "OneIfByLand";
_webTester.setTextField("username", username);
_webTester.setTextField("password", password);
_webTester.submit();
_webTester.assertTitleEquals("Confirm Registration Information");
_webTester.assertTextPresent(username);
_webTester.assertTextPresent(password);
_webTester.submit();
_webTester.assertTitleEquals("Success!");
_webTester.assertTextPresent("Thanks for registering!");
}
@Test
public void testScenario1EmptyInputFields() {
_webTester.beginAt("/login.jsp");
_webTester.submit();
assertLoginPageWithErrorMessage("All fields are required! Try again! Don't make me go back there!");
}
/*
* The code for these methods is the same. Refactored them.
*/
@Test
public void testScenario1InvalidNameInputNumeric() {
assertFieldNumericErrorFound("thx1138", "hi", "Yo! The username can only contain letters!");
}
@Test
public void testScenario1InvalidPasswordInputNumeric() {
assertFieldNumericErrorFound("Paul Revere", "thx1138", "Yo! The password can only contain letters!");
}
private void assertFieldNumericErrorFound(String username, String password,
String errMsg) {
_webTester.beginAt("/login.jsp");
_webTester.setTextField("username", username);
_webTester.setTextField("password", password);
_webTester.submit();
assertLoginPageWithErrorMessage(errMsg);
}
/*
* The code for these methods is the same. Refactored them.
*/
@Test
public void testScenario1InvalidNameInputLength() {
assertFieldLengthErrorFound("abcdefghijklmnopqrstuvwxyzABCDE", "hi", "Yo! The username can only be 30 letters or less!");
}
@Test
public void testScenario1InvalidPasswordInputLength() {
assertFieldLengthErrorFound("Paul Revere", "abcdefghijklmnopqrstuvwxyzABCDE", "Yo! The password can only be 30 letters or less!");
}
private void assertFieldLengthErrorFound(String username, String password,
String errMsg) {
_webTester.beginAt("/login.jsp");
_webTester.setTextField("username", username);
_webTester.setTextField("password", password);
_webTester.submit();
assertLoginPageWithErrorMessage(errMsg);
}
@Test
public void testScenario1UnknownErrorOnSubmit() {
_webTester.beginAt("/login.jsp");
String username = "Force an error";
String password = "VeryBad";
_webTester.setTextField("username", username);
_webTester.setTextField("password", password);
_webTester.submit();
assertLoginPageWithErrorMessage("I'm sorry, but we seem to have encountered an error. Please try again later or contact Hidden Clause customer support.");
}
@Test
public void testScenario2UserReEntersRegistrationInformation() {
_webTester.beginAt("/login.jsp");
String username = "Paul Revere";
String password = "OneIfByLand";
_webTester.setTextField("username", username);
_webTester.setTextField("password", password);
_webTester.submit();
_webTester.assertTitleEquals("Confirm Registration Information");
_webTester.submit("edit");
_webTester.assertTitleEquals("Welcome! Register here!");
_webTester.assertTextFieldEquals("username", username);
_webTester.assertTextFieldEquals("password", password);
}
@Test
public void testScenario3SystemErrorOnConfirm() {
_webTester.beginAt("/login.jsp");
String username = "Confirmation error";
String password = "OneIfByLand";
_webTester.setTextField("username", username);
_webTester.setTextField("password", password);
_webTester.submit();
_webTester.assertTitleEquals("Confirm Registration Information");
_webTester.submit();
assertLoginPageWithErrorMessage("I'm sorry, but we seem to have encountered an error. Please try again later or contact Hidden Clause customer support.");
}
private void assertLoginPageWithErrorMessage(String errorMessage) {
_webTester.assertTitleEquals("Welcome! Register here!");
_webTester.assertTextPresent(errorMessage);
}
}
login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@page import="java.util.regex.Pattern"%>
<%@page import="java.util.regex.Matcher"%>
<%!
private Pattern _pattern = Pattern.compile("[0-9]");
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Welcome! Register here!</title>
</head>
<body>
<%
String msg = null;
String submit = request.getParameter("submit");
String username = request.getParameter("username");
String password = request.getParameter("password");
if (submit != null && submit.equals("Submit")) {
if (username == null
|| username.trim().length() == 0
|| password == null
|| password.trim().length() == 0) {
msg = "All fields are required! Try again! Don't make me go back there!";
} else if (username.equals("Force an error")) {
msg = "I'm sorry, but we seem to have encountered an error. Please try again later or contact Hidden Clause customer support.";
} else {
Matcher matcher = _pattern.matcher(username);
if (matcher.find()) {
msg = "Yo! The username can only contain letters!";
} else if (username.trim().length() > 30) {
msg = "Yo! The username can only be 30 letters or less!";
} else {
matcher = _pattern.matcher(password);
if (matcher.find()) {
msg = "Yo! The password can only contain letters!";
} else if (password.trim().length() > 30) {
msg = "Yo! The password can only be 30 letters or less!";
}
}
}
if (msg == null) {
request.getRequestDispatcher("confirmation.jsp").forward(request, response);
} else {
%>
<span style="color: red;"><%=msg %></span>
<%
}
}
%>
<form action="login.jsp">
<input name="username" value='<%=username != null ? username : "" %>'>
<input name="password" type="hidden" value='<%= password != null ? password : "" %>'>
<input type="submit" value="Submit" name="submit">
</form>
</body>
</html>
confirmation.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Confirm Registration Information</title>
</head>
<body>
<%
String username = request.getParameter("username");
String password = request.getParameter("password");
%>
Name: <%= username %>
Password: <%= password %>
<form action="success.jsp">
<input type="hidden" name="username" value="<%=username %>">
<input type="hidden" name="password" value="<%=password %>">
<input type="submit" value="Submit">
</form>
<form action="login.jsp?">
<input type="hidden" name="username" value="<%=username %>">
<input type="hidden" name="password" value="<%=password %>">
<input type="submit" name="edit" value="Edit">
</form>
</body>
</html>
success.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%
String username = request.getParameter("username");
if (username.equals("Confirmation error")) {
request.getRequestDispatcher("login.jsp?username=Force%20an%20error&submit=Submit").forward(request, response);
}
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Success!</title>
</head>
<body>
Thanks for registering!
</body>
</html>
Writing an Eclipse Plug-in (Part 13): Common Navigator: Adding Tests
And now it is time for the mundane.
While I firmly believe in test-driven development I do not believe in test-driven learning; that means that while tests are great to insure that your software works as advertised (or at least as much of it as you could think of), testing is not a good way to learn implementation. I know the physicists out there will disagree with me, but learning the black box behavior of a system is quite different than learning how to build the actual clockwork mechanism that makes something go.
With that said, at some point we do need to refactor the code and we can’t safely refactor the code without some tests to prove that our refactoring hasn’t broken anything.
We have been coding without a net in the interest of keeping the learning as noise-free as possible. Now we return to the part of the coding that we would normally do as we developed the code.
In other words, time for code hygiene.
What to do
- Create a plug-in test project for the navigator
- Enter the following:
- Project name: customnavigator.test
- Eclipse version: 3.5
- Click Next
- Enter the following:
- Version: 1.0.1.3 [Actually anything you want]
- Name: Custom Navigator Test
- Click Finish
- Enter the following:
- Clean up MANIFEST.MF
- Click the MANIFEST.MF tab
- Move the cursor to line 1 and Press Ctrl+1
- Select Add Missing Packages
- Move the cursor to line 3 and Press Ctrl+1
- Select Externalize the Bundle-Name header
- Save the file
- Dependencies tab: Add org.junit4
- Dependencies tab: Add org.eclipse.core.resources
- Copy easymock.jar to your project. Add a lib folder under your test project folder, copy the easymock.jar file and add it to Runtime –> Classpath
- Open the customnavigator.test Properties dialog. In the Project References element put a check mark next to the customnavigator project. Click Finish.
- Implement customnavigator.navigator.ContentProviderTest in the customnavigator.test project
- Create a new JUnit class named customnavigator.navigator.ContentProviderTest
- Test getParent()
- Test getChildren()
- Test hasChildren()
One of the tests, getChildren(), pointed out a bug: when a project came in, custom or not, it was being wrapped and saved in the _wrapperCache. The only projects that should be in the wrapper cache are projects of type CustomProjectParents. While not fatal, it was still wrong. Not a bad catch.
Here is the corrected code.
ContentProvider.java
private Object[] createCustomProjectParents(IProject[] projects) {
Object[] result = null;
List<Object> list = new ArrayList<Object>();
for (int i = 0; i < projects.length; i++) {
Object customProjectParent = _wrapperCache.get(projects[i].getName());
if (customProjectParent == null) {
customProjectParent = createCustomProjectParent(projects[i]);
if (customProjectParent != null) {
_wrapperCache.put(projects[i].getName(), customProjectParent);
}
}
if (customProjectParent != null) {
list.add(customProjectParent);
} // else ignore the project
}
result = new Object[list.size()];
list.toArray(result);
return result;
}
That brings the number of test projects up to 2.
Why did we do that?
Just as a review about TDD from my rather narrow/myopic perspective (and not necessarily in this order):
- Don’t test the platform
- Don’t test trivial logic (i.e. trivial getters and setters)
- Test boundary conditions that will cause errors
- Test success conditions
So, what kinds of tests do we need? Well, the easiest way is to pretend we know how to implement the behavior, but haven’t actually written it yet. That should give us a clarity of purpose known only to those who already know the answer.
What does Eclipse expect the content provider to provide? Well, content. In our case, the content is the custom project in its variations; no other project/content types need apply.
As ContentProvider is just another POJO we can test it in a pretty standalone way. Also, even though our content provider implements an interface that extends an interface that extends an interface, we really only care about the methods we overrode. Of course, when I made the following list to see which methods I care about it turns out I had to override them all:
public class ContentProvider implements ITreeContentProvider, IResourceChangeListener {
// From ITreeContentProvider
@Override
public Object[] getChildren(Object parentElement) {
...
}
@Override
public Object getParent(Object element) {
...
}
@Override
public boolean hasChildren(Object element) {
...
}
// From IStructuredContentProvider
@Override
public Object[] getElements(Object inputElement) {
...
}
// From IContentProvider
@Override
public void dispose() {
...
}
@Override
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
...
}
// From IResourceChangeListener
@Override
public void resourceChanged(IResourceChangeEvent event) {
...
}
}
The EasyMock framework will also make these tests a simpler to implement. I am not going to try to convince you one way or another to use EasyMock or any other mock object framework. Every time I use EasyMock my life is easier. If there is a simpler mock object framework let me know, otherwise pick one and get to work.
For example, when I thought about the tests for ContentProvider I wasn’t sure which I should write first so I took the path of least resistence:
- getParent()
- Input: IWorkspaceRoot, Output: null
- Input: IProject, Output: non-null
- Input: ICustomProjectElement, Output: non-null (could be an IWorkspaceRoot, or one of the CustomProject wrappers)
- Input: anything else (including null), Output: zero length array
- getChildren()
- Input: IWorkspaceRoot, Output: null if no projects exist or if the projects are not of of the Custom Project nature.
- Input: IWorkspaceRoot, Output: non-null if a Custom Project exists
- Input: IWorkspaceRoot w/ 3 projects (1 non-custom, 1 custom, 1 non-custom), Output: an array with one custom project
- Input: IWorkspaceRoot w/ 3 projects (1 custom, 1 non-custom, 1 custom), Output: an array with two custom projects
- Input: IProject, Output: null (by defintion, if it were a CustomProject it would be wrapped already)
- Input: ICustomProjectElement, Output: non-null unless if is a leaf child like CustomProjectSchemaFilters
- Input: anything else (including null), Output: zero length array
- hasChildren()
- Input: IWorkspaceRoot, Output: false if the projects no proejcts exist or are not Custom Projects otherwise true
- Input: ICustomProjectElement, Output: false if it is a leaf child like CustomProjectSchemaFilters, true otherwise
- Input: anything else (including null), Output: false
Seems like a lot to think about doesn’t it? That is the whole idea. [Programming is no more about typing than writing is; in fact, programming is just as much about thinking as writing is.] Under what conditions can something fail? When it “succeeds” did it succeed properly? Some of the above I normally consider as I write the tests and others happen as I learn about the behavior as I implement. White boards are my friend.
Also, tests, like the ones for ICustomProjectElement, normally help you discover that you need data types like ICustomProjectElement. In this case, we skipped a few steps.
It’s okay; I forgive us.
Finally, I am not testing:
- getElement(): since this calls getChildren() there is no reason to test this.
- dispose(): I have no idea how I would do that. Sadly, I do have to make sure that I release any resources for which I am responsible, but I am not sure how I would do that except to simply remember that I need to do that in dispose() (can you say time bomb?). Also, it is trivial enough so I can safely ignore it for now.
- inputChanged(): having implemented it I can safely say that testing an assignment at this point is…pointless.
- resourceChanged(): This is purely GUI behavior. I suppose I could test it if the logic were complex, but for now it is not.
Being less than a TDD purist is hard to admit, but what the heck, I am not as much of a TDD purist as I would like folks to believe. Sometimes, I can’t come up with that perfect scenario that will light the way for me to create a host of absolutely incredible tests that will leave my code both bug-free and completely covered.
In any case, I am not going to go over every test or how I agonized over them or how much I drank to get through them. Red Bull is overrated.
In addition, clean up customnavigator.test.Activator:
– comment the empty constructor
– add @Override to start()
– add @Override to stop()
More True Confessions
And this is where we write all kinds of test code for the CustomNavigator; only CustomProjects should appear and their various nodes should stay open if they were open when we changed something or should stay closed when we changed something.
We could test things like:
- a generic project – assert an empty custom navigator in a fresh workspace
- a custom project – assert one project in the custom navigator
- a generic project and a custom project – assert one project in the custom navigator
There is only one problem (or perhaps we should consider it an opportunity): that is testing the platform. Making sure that ContentProvider is called with an IWorkspaceRoot was a plugin.xml configuration, not code, so what are we testing anyway? Actually, we would be testing the ContentProvider! Again!
I know we had fun doing it the first time, but I’ll pass on doing it more than once.
I am also not going to write any tests for CustomProjectParent or any of the children that come from it. Why? They are simple. No point wasting time on them until the logic contained by them is complex enough to warrant it.
Kinda makes you wish we had refactored them earlier. No worries; we do that in the next post.
What Just Happened?
Some of you may look at the tests and wonder how does using EasyMock make the job any easier? It is not about EasyMock; it is about testing the expected behavior from the code regardless of what the actual input is.
For example, in testGetChildrenForICustomProjectElementWithNoChildren() and testGetChildrenForICustomProjectElementWithChildren() I tested for an ICustomProjectElement with children and with no children, but I did it without using the CustomProjectParent type or any of its children. The reason for that is both simple and important: I am not testing CustomProjectParent or its children; I am testing ContentProvider. By mixing the testing of ContentProvider and CustomProjectParent (or any of the children) I run the risk of testing something I don’t need to test, or worse, forgetting to test something I should have tested.
Next time: Now that the tests are mostly out of the way it is time to refactor the children.
The cat is tired.
Code
ContentProviderTest.java
/**
* Coder beware: this code is not warranted to do anything.
*
* Copyright Dec 6, 2009 Carlos Valcarcel
*/
package customnavigator.navigator;
import org.easymock.EasyMock;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectNature;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.runtime.CoreException;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
/**
* @author carlos
*
*/
public class ContentProviderTest {
private static final String CUSTOMPLUGIN_PROJECT_NATURE = "customplugin.projectNature"; //$NON-NLS-1$
private ContentProvider _contentProvider;
@Test
public void testGetParentForIWorkspaceRoot() {
Object actual = null;
IWorkspaceRoot workspaceRoot = EasyMock.createStrictMock(IWorkspaceRoot.class);
actual = _contentProvider.getParent(workspaceRoot);
Assert.assertNull(actual);
}
@Test
public void testGetParentForNull() {
Object actual = null;
actual = _contentProvider.getParent(null);
Assert.assertNull(actual);
}
@Test
public void testGetParentForObject() {
Object actual = null;
actual = _contentProvider.getParent(new Object());
Assert.assertNull(actual);
}
@Test
public void testGetParentForIProject() {
IWorkspaceRoot workspaceRoot = EasyMock.createStrictMock(IWorkspaceRoot.class);
IWorkspace workspace = EasyMock.createStrictMock(IWorkspace.class);
IProject project = EasyMock.createStrictMock(IProject.class);
project.getWorkspace();
EasyMock.expectLastCall().andReturn(workspace);
workspace.getRoot();
EasyMock.expectLastCall().andReturn(workspaceRoot);
EasyMock.replay(workspaceRoot, workspace, project);
Object actual = _contentProvider.getParent(project);
Assert.assertNotNull(actual);
EasyMock.verify(workspaceRoot, workspace, project);
}
@Test
public void testGetParentForICustomProjectElement() {
Object parent = EasyMock.createNiceControl();
ICustomProjectElement customProjectElement = EasyMock.createStrictMock(ICustomProjectElement.class);
customProjectElement.getParent();
EasyMock.expectLastCall().andReturn(parent);
EasyMock.replay(customProjectElement);
Object actual = _contentProvider.getParent(customProjectElement);
Assert.assertNotNull(actual);
EasyMock.verify(customProjectElement);
}
@Test
public void testGetChildrenForIWorkspaceRootWithNoProjects() {
IProject [] projects = {};
IWorkspaceRoot workspaceRoot = EasyMock.createStrictMock(IWorkspaceRoot.class);
workspaceRoot.getProjects();
EasyMock.expectLastCall().andReturn(projects);
EasyMock.replay(workspaceRoot);
Object [] actual = _contentProvider.getChildren(workspaceRoot);
Assert.assertNotNull(actual);
Assert.assertTrue(actual.length == 0);
EasyMock.verify(workspaceRoot);
}
@Test
public void testGetChildrenForIWorkspaceRootWithNoCustomProjects() throws CoreException {
IProject [] projects = new IProject[1];
IProject project = EasyMock.createStrictMock(IProject.class);
projects[0] = project;
IWorkspaceRoot workspaceRoot = EasyMock.createStrictMock(IWorkspaceRoot.class);
workspaceRoot.getProjects();
EasyMock.expectLastCall().andReturn(projects);
project.getName();
EasyMock.expectLastCall().andReturn("non-custom project"); //$NON-NLS-1$
project.getNature(CUSTOMPLUGIN_PROJECT_NATURE);
EasyMock.expectLastCall().andReturn(null);
EasyMock.replay(workspaceRoot, project);
Object [] actual = _contentProvider.getChildren(workspaceRoot);
Assert.assertNotNull(actual);
Assert.assertTrue(actual.length == 0);
EasyMock.verify(workspaceRoot, project);
}
@Test
public void testGetChildrenForIWorkspaceRootWithOneCustomProject() throws CoreException {
IProject [] projects = new IProject[1];
IProject project = EasyMock.createStrictMock(IProject.class);
projects[0] = project;
IWorkspaceRoot workspaceRoot = EasyMock.createStrictMock(IWorkspaceRoot.class);
workspaceRoot.getProjects();
EasyMock.expectLastCall().andReturn(projects);
String projectName = "custom project"; //$NON-NLS-1$
project.getName();
EasyMock.expectLastCall().andReturn(projectName);
project.getNature(CUSTOMPLUGIN_PROJECT_NATURE);
EasyMock.expectLastCall().andReturn(EasyMock.createMock(IProjectNature.class));
project.getName();
EasyMock.expectLastCall().andReturn(projectName);
EasyMock.replay(workspaceRoot, project);
Object [] actual = _contentProvider.getChildren(workspaceRoot);
Assert.assertNotNull(actual);
Assert.assertTrue(actual.length == 1);
Assert.assertEquals(project, ((CustomProjectParent)actual[0]).getProject());
EasyMock.verify(workspaceRoot, project);
}
@Test
public void testGetChildrenForIWorkspaceRootWithOneCustomProjectTwoNonCustomProjects() throws CoreException {
IProject nonCustomProject1 = EasyMock.createStrictMock(IProject.class);
IProject nonCustomProject2 = EasyMock.createStrictMock(IProject.class);
IProject customProject = EasyMock.createStrictMock(IProject.class);
IProject[] projects = {
nonCustomProject1,
customProject,
nonCustomProject2
};
IWorkspaceRoot workspaceRoot = EasyMock.createStrictMock(IWorkspaceRoot.class);
workspaceRoot.getProjects();
EasyMock.expectLastCall().andReturn(projects);
String bogusProjectName = "bogus project"; //$NON-NLS-1$
String customProjectName = "custom project"; //$NON-NLS-1$
nonCustomProject1.getName();
EasyMock.expectLastCall().andReturn(bogusProjectName);
nonCustomProject1.getNature(CUSTOMPLUGIN_PROJECT_NATURE);
EasyMock.expectLastCall().andReturn(null);
customProject.getName();
EasyMock.expectLastCall().andReturn(customProjectName);
customProject.getNature(CUSTOMPLUGIN_PROJECT_NATURE);
EasyMock.expectLastCall().andReturn(EasyMock.createMock(IProjectNature.class));
customProject.getName();
EasyMock.expectLastCall().andReturn(customProjectName);
nonCustomProject2.getName();
EasyMock.expectLastCall().andReturn(bogusProjectName);
nonCustomProject2.getNature(CUSTOMPLUGIN_PROJECT_NATURE);
EasyMock.expectLastCall().andReturn(null);
EasyMock.replay(workspaceRoot, nonCustomProject1, customProject, nonCustomProject2);
Object [] actual = _contentProvider.getChildren(workspaceRoot);
Assert.assertNotNull(actual);
Assert.assertTrue(actual.length == 1);
Assert.assertEquals(customProject, ((CustomProjectParent)actual[0]).getProject());
EasyMock.verify(workspaceRoot, nonCustomProject1, nonCustomProject2, customProject);
}
@Test
public void testGetChildrenForIWorkspaceRootWithOneNonCustomProjectTwoCustomProjects() throws CoreException {
IProject customProject1 = EasyMock.createStrictMock(IProject.class);
IProject customProject2 = EasyMock.createStrictMock(IProject.class);
IProject nonCustomProject = EasyMock.createStrictMock(IProject.class);
IProject[] projects = {
customProject1,
nonCustomProject,
customProject2
};
IWorkspaceRoot workspaceRoot = EasyMock.createStrictMock(IWorkspaceRoot.class);
workspaceRoot.getProjects();
EasyMock.expectLastCall().andReturn(projects);
String bogusProjectName = "bogus project"; //$NON-NLS-1$
String customProjectName1 = "custom project 1"; //$NON-NLS-1$
String customProjectName2 = "custom project 2"; //$NON-NLS-1$
customProject1.getName();
EasyMock.expectLastCall().andReturn(customProjectName1);
customProject1.getNature(CUSTOMPLUGIN_PROJECT_NATURE);
EasyMock.expectLastCall().andReturn(EasyMock.createMock(IProjectNature.class));
customProject1.getName();
EasyMock.expectLastCall().andReturn(customProjectName1);
nonCustomProject.getName();
EasyMock.expectLastCall().andReturn(bogusProjectName);
nonCustomProject.getNature(CUSTOMPLUGIN_PROJECT_NATURE);
EasyMock.expectLastCall().andReturn(null);
customProject2.getName();
EasyMock.expectLastCall().andReturn(customProjectName2);
customProject2.getNature(CUSTOMPLUGIN_PROJECT_NATURE);
EasyMock.expectLastCall().andReturn(EasyMock.createMock(IProjectNature.class));
customProject2.getName();
EasyMock.expectLastCall().andReturn(customProjectName2);
EasyMock.replay(workspaceRoot, customProject1, nonCustomProject, customProject2);
Object [] actual = _contentProvider.getChildren(workspaceRoot);
Assert.assertNotNull(actual);
Assert.assertTrue(actual.length == 2);
Assert.assertEquals(customProject1, ((CustomProjectParent)actual[0]).getProject());
Assert.assertEquals(customProject2, ((CustomProjectParent)actual[1]).getProject());
EasyMock.verify(workspaceRoot, customProject1, nonCustomProject, customProject2);
}
/**
* If a resource of type IProject comes in ignore it. If it were
* a Custom Project it would be wrapped already.
*/
@Test
public void testGetChildrenForIProjectNotCustomProject() {
IProject project = EasyMock.createStrictMock(IProject.class);
Object [] actual = _contentProvider.getChildren(project);
Assert.assertNotNull(actual);
Assert.assertTrue(actual.length == 0);
}
@Test
public void testGetChildrenForICustomProjectElementWithNoChildren() {
assertChildrenFromICustomProjectElement(0);
}
/**
* Check that an ICustomProjectElement returns some kids. Send back 5 to prove
* the right method is called.
*/
@Test
public void testGetChildrenForICustomProjectElementWithChildren() {
assertChildrenFromICustomProjectElement(5);
}
@Before
public void setUp() {
_contentProvider = new ContentProvider();
}
private void assertChildrenFromICustomProjectElement(int childCount) {
Object [] children = new Object[childCount];
ICustomProjectElement customProjectElement = EasyMock.createStrictMock(ICustomProjectElement.class);
customProjectElement.getChildren();
EasyMock.expectLastCall().andReturn(children);
EasyMock.replay(customProjectElement);
Object [] actual = _contentProvider.getChildren(customProjectElement);
Assert.assertNotNull(actual);
Assert.assertTrue(actual.length == childCount);
EasyMock.verify(customProjectElement);
}
}
ContentProvider.java
/**
* Coder beware: this code is not warranted to do anything.
* Copyright Oct 17, 2009 Carlos Valcarcel
*/
package customnavigator.navigator;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResourceChangeEvent;
import org.eclipse.core.resources.IResourceChangeListener;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.TreePath;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import customplugin.natures.ProjectNature;
/**
* @author carlos
*/
public class ContentProvider implements ITreeContentProvider, IResourceChangeListener {
private static final Object[] NO_CHILDREN = {};
private Map<String, Object> _wrapperCache = new HashMap<String, Object>();
private Viewer _viewer;
public ContentProvider() {
ResourcesPlugin.getWorkspace().addResourceChangeListener(this, IResourceChangeEvent.POST_CHANGE);
}
/*
* (non-Javadoc)
* @see
* org.eclipse.jface.viewers.ITreeContentProvider#getChildren(java.lang.Object)
*/
@Override
public Object[] getChildren(Object parentElement) {
Object[] children = null;
if (IWorkspaceRoot.class.isInstance(parentElement)) {
IProject[] projects = ((IWorkspaceRoot)parentElement).getProjects();
children = createCustomProjectParents(projects);
} else if (ICustomProjectElement.class.isInstance(parentElement)) {
children = ((ICustomProjectElement) parentElement).getChildren();
} else {
children = NO_CHILDREN;
}
return children;
}
/*
* (non-Javadoc)
* @see
* org.eclipse.jface.viewers.ITreeContentProvider#getParent(java.lang.Object)
*/
@Override
public Object getParent(Object element) {
Object parent = null;
if (IProject.class.isInstance(element)) {
parent = ((IProject)element).getWorkspace().getRoot();
} else if (ICustomProjectElement.class.isInstance(element)) {
parent = ((ICustomProjectElement)element).getParent();
} // else parent = null if IWorkspaceRoot or anything else
return parent;
}
/*
* (non-Javadoc)
* @see
* org.eclipse.jface.viewers.ITreeContentProvider#hasChildren(java.lang.Object)
*/
@Override
public boolean hasChildren(Object element) {
boolean hasChildren = false;
if (IWorkspaceRoot.class.isInstance(element)) {
hasChildren = ((IWorkspaceRoot)element).getProjects().length > 0;
} else if (ICustomProjectElement.class.isInstance(element)) {
hasChildren = ((ICustomProjectElement)element).hasChildren();
}
// else it is not one of these so return false
return hasChildren;
}
/*
* (non-Javadoc)
* @see
* org.eclipse.jface.viewers.IStructuredContentProvider#getElements(java.lang.Object)
*/
@Override
public Object[] getElements(Object inputElement) {
// This is the same as getChildren() so we will call that instead
return getChildren(inputElement);
}
/*
* (non-Javadoc)
* @see org.eclipse.jface.viewers.IContentProvider#dispose()
*/
@Override
public void dispose() {
ResourcesPlugin.getWorkspace().removeResourceChangeListener(this);
}
/*
* (non-Javadoc)
* @see
* org.eclipse.jface.viewers.IContentProvider#inputChanged(org.eclipse.jface.viewers.Viewer, java.lang.Object, java.lang.Object)
*/
@Override
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
_viewer = viewer;
}
@Override
public void resourceChanged(IResourceChangeEvent event) {
TreeViewer viewer = (TreeViewer) _viewer;
TreePath[] treePaths = viewer.getExpandedTreePaths();
viewer.refresh();
viewer.setExpandedTreePaths(treePaths);
}
private Object createCustomProjectParent(IProject parentElement) {
Object result = null;
try {
if (parentElement.getNature(ProjectNature.NATURE_ID) != null) {
result = new CustomProjectParent(parentElement);
}
} catch (CoreException e) {
// Go to the next IProject
}
return result;
}
private Object[] createCustomProjectParents(IProject[] projects) {
Object[] result = null;
List<Object> list = new ArrayList<Object>();
for (int i = 0; i < projects.length; i++) {
Object customProjectParent = _wrapperCache.get(projects[i].getName());
if (customProjectParent == null) {
customProjectParent = createCustomProjectParent(projects[i]);
if (customProjectParent != null) {
_wrapperCache.put(projects[i].getName(), customProjectParent);
}
}
if (customProjectParent != null) {
list.add(customProjectParent);
} // else ignore the project
}
result = new Object[list.size()];
list.toArray(result);
return result;
}
}
JGAP: A First/Simple Tutorial
(This is going to be a long one.)
Genetic Programming. The only thing that strikes more fear in my heart is Lisp. Another blogger whose post I can’t find described learning Lisp as being similar to scaling a vertical wall. I have spent quite a bit of time reading about Lisp and sadly have to agree.
However, I have hope. I am reading Peter Norvig’s Paradigms of Artificial Intelligence Programming and while it is endlessly fascinating the Lisp is only marginally more appealing. He does a great job of describing certain Lisp concepts in a way that even I can understand. The chapter on Eliza is one of the best of the book.
Another on the scale of interesting, but daunting, software concepts, is Genetic Programming (GP). After reading the chapter of genetic programming (Evolving Intelligence) in Toby Segaran’s book Programming Collective Intelligence I found my interest rather piqued and started to look deeper and deeper into GP. I follow a lot of topics related to software, but most I only follow enough to know they exist and may or may not be interesting. GP has always been on the interesting side, but with the potential to be quite involved.
After reading the chapter on GP in Programming Collective Intelligence, and forcing a number of my colleagues to read it as well, I came away thinking that perhaps it was time to start delving into it. After all, it looks hard and if it looks hard it must be worth looking trying.
<MyThoughts>
Hmm.
Python. Looks a lot like Lisp.
Uses lambda functions. Looks a lot like Java inner classes without all the syntactic sugar.
Cool. Small functions. Maybe I should learn more Python after all…
Running it from the Python command line interpreter. Interesting. I wonder how hard that would be to do in Eclipse? I have only used Pydev for small Python objects at work.
Hmm. The code creates a number of wrappers to functions.
Primitive tests.
Wouldn’t I have to write a lot of Java to duplicate this? Might be an interesting project, but looks tedious.
…
</MyThoughts>
Over time I had collected links to various open source projects about GP, but it was not until I read the Segaran chapter that I decided to look at any of them.
I settled on JGAP. Why? Laziness…I mean…less work. That’s it; less work. Also, it is written in Java so I feel comforted.
JGAP purports to do quite a bit of work for the developer, but allows you to extend things if you so choose. There are a number of examples shipped with the framework so how hard can it be?
The example from the GP chapter in Collective Intelligence looks like this: here are a list of inputs and their associated output (Programming Collective Intelligence, page 259):
| Input 1 | Input 2 | Output |
| 26 | 35 | 829 |
| 8 | 24 | 141 |
| 20 | 1 | 467 |
| 33 | 11 | 1215 |
| 37 | 16 | 1517 |
The point of the exercise is to discover what equation will return the result given the 2 input values. The answer is x^2+2y+3x+5 where x is input 1 and y is input 2 (Programming Collective Intelligence, page 259).
Eventually, the Python code breeds a solution that looks like this (Programming Collective Intelligence, page 267):
(X*(2+X))+X+4+Y+Y+(10>5)
If you simplify the above you get:
2x+x^2+x+4+2y+1 x^2+2x+x+2y+4+1 x^2+3x+2y+5
Which is pretty much what Toby Segaran was looking for. He briefly talks about how inefficient the code out of a genetically created program can be, but it is pretty awesome in any case.
If you want to take a look at the Python code that was used then read the sample chapter on Safari Books Online.
So today’s goal is: duplicate the Python result with JGAP using the least amount of code possible. How to do that?
I am not going to discuss GP in any real depth. I want to get JGAP up and running and see what I can do with a simple example.
The JGAP document lists 4 steps involved in creating a GP using JGAP:
- Create a GP Configuration Object
- Create an initial Genotype
- Evolve the population
- Optionally implement custom functions and terminals (a mutable static number)
The JGAP documentation leaves out the use of a fitness function in their GP section, even though you have to use one and they have one implemented. I would list that as the first thing you should do.
In Test-driven Development it would be:
- Write a test
- Write whatever code it takes to pass the test
- Refactor the code so you won’t be embarrassed when your mom sees it
- Repeat
If we think of the fitness function as a test program then we can think of GP as a type of programming that can make use of TDD. In fact, the folks at NeoCoreTechs are working on extreme genetic programming (XGP) as a way of growing applications rather than writing them. Sounds like a noble goal, but a hard one. In other words, sounds like it’s worth doing.
Let’s port the example from the Programming Collective Intelligence book to JGAP.
Implement a Fitness Function
The fitness function (unit test for you TDD’ers) needs to score the incoming chromosomes/solutions. The original Python fitness function is:
def scorefunction(tree,s):
dif=0
for data in s:
v=tree.evaluate([data[0],data[1]])
dif+=abs(v-data[2])
return dif
As the value returned by the chromosome gets closer to the desired output the result of the subtraction gets closer to 0.
The Java evaluate():double method looks like:
protected double evaluate(final IGPProgram program) {
double result = 0.0f;
long longResult = 0;
for (int i = 0; i < _input1.length; i++) {
// Set the input values
_xVariable.set(_input1[i]);
_yVariable.set(_input2[i]);
// Execute the genetically engineered algorithm
long value = program.execute_int(0, NO_ARGS);
// The closer longResult gets to 0 the better the algorithm.
longResult += Math.abs(value - _output[i]);
}
result = longResult;
return result;
}
(I know: I could have gotten away with just the longResult and let the return do an autoboxing, but I didn’t want to.)
Looks rather similar to the original Python code only with autoboxing. The _xVariable and _yVariable are references to objects under the control of the chromosomes in the population and having them means we can give the chromosomes new values to help them do their job: figuring out what the formula is that will get us the desired output.
Create a GP Configuration Object
I have the SimpleMathTest class initialize itself in its constructor so this is where I create the GPConfiguration object. Values for the maximum initialization depth, population size and maximum crossover depth are arbitrary for now. These are numbers I found used in some of the other JGAP examples and figured they were good enough.
In addition, I assigned the fitness function to GPConfiguration using setFitnessFunction().
public SimpleMathTest() throws InvalidConfigurationException {
super(new GPConfiguration());
GPConfiguration config = getGPConfiguration();
_xVariable = Variable.create(config, "X", CommandGene.IntegerClass);
_yVariable = Variable.create(config, "Y", CommandGene.IntegerClass);
config.setGPFitnessEvaluator(new DeltaGPFitnessEvaluator());
config.setMaxInitDepth(4);
config.setPopulationSize(1000);
config.setMaxCrossoverDepth(8);
config.setFitnessFunction(new SimpleMathTestFitnessFunction(INPUT_1, INPUT_2, OUTPUT, _xVariable, _yVariable));
config.setStrictProgramCreation(true);
}
Create an initial genotype
The genotype represents a configured GP environment. This is where we pass the references to _xVariable and _yVariable used by the fitness function.
public GPGenotype create() throws InvalidConfigurationException {
GPConfiguration config = getGPConfiguration();
// The return type of the GP program.
Class[] types = { CommandGene.IntegerClass };
// Arguments of result-producing chromosome: none
Class[][] argTypes = { {} };
// Next, we define the set of available GP commands and terminals to
// use.
CommandGene[][] nodeSets = {
{
_xVariable,
_yVariable,
new Add(config, CommandGene.IntegerClass),
new Multiply(config, CommandGene.IntegerClass),
new Terminal(config, CommandGene.IntegerClass, 0.0, 10.0, true)
}
};
GPGenotype result = GPGenotype.randomInitialGenotype(config, types, argTypes,
nodeSets, 20, true);
return result;
}
Evolve the population
At this stage all we are doing is creating the population, which calls the fitness function, and checking to see if our test values match.
GPGenotype gp = problem.create();
gp.setVerboseOutput(true);
gp.evolve(30);
System.out.println("Formula to discover: x^2 + 2y + 3x + 5");
gp.outputSolution(gp.getAllTimeBest());
The final output from all the above work is (and this may vary based on the created population):
(Y + Y) + ((5 + X) + ((X * X) + (X + X)))
which, when simplified, becomes the desired formula. Not bad for a few hours work. Of course, I did not come up with this in my first pass. I hit a dead end at one point and refactored like mad once I had it working, but the results are impressive given that I worked on it for a short amount of time.
The Actual Pieces
The fitness function in class SimpleMathTestFitnessFunction:
package hiddenclause.example;
import org.jgap.gp.GPFitnessFunction;
import org.jgap.gp.IGPProgram;
import org.jgap.gp.terminal.Variable;
public class SimpleMathTestFitnessFunction extends GPFitnessFunction {
private Integer[] _input1;
private Integer[] _input2;
private int[] _output;
private Variable _xVariable;
private Variable _yVariable;
private static Object[] NO_ARGS = new Object[0];
public SimpleMathTestFitnessFunction(Integer input1[], Integer input2[],
int output[], Variable x, Variable y) {
_input1 = input1;
_input2 = input2;
_output = output;
_xVariable = x;
_yVariable = y;
}
@Override
protected double evaluate(final IGPProgram program) {
double result = 0.0f;
long longResult = 0;
for (int i = 0; i < _input1.length; i++) {
// Set the input values
_xVariable.set(_input1[i]);
_yVariable.set(_input2[i]);
// Execute the genetically engineered algorithm
long value = program.execute_int(0, NO_ARGS);
// The closer longResult gets to 0 the better the algorithm.
longResult += Math.abs(value - _output[i]);
}
result = longResult;
return result;
}
}
The actual GP program to find the secret formula in class SimpleMathTest:
package hiddenclause.example;
import org.jgap.InvalidConfigurationException;
import org.jgap.gp.CommandGene;
import org.jgap.gp.GPProblem;
import org.jgap.gp.function.Add;
import org.jgap.gp.function.Multiply;
import org.jgap.gp.function.Pow;
import org.jgap.gp.impl.DeltaGPFitnessEvaluator;
import org.jgap.gp.impl.GPConfiguration;
import org.jgap.gp.impl.GPGenotype;
import org.jgap.gp.terminal.Terminal;
import org.jgap.gp.terminal.Variable;
/**
* @author carlos
*
*/
public class SimpleMathTest extends GPProblem {
@SuppressWarnings("boxing")
private static Integer[] INPUT_1 = { 26, 8, 20, 33, 37 };
@SuppressWarnings("boxing")
private static Integer[] INPUT_2 = { 35, 24, 1, 11, 16 };
private static int[] OUTPUT = { 829, 141, 467, 1215, 1517 };
private Variable _xVariable;
private Variable _yVariable;
public SimpleMathTest() throws InvalidConfigurationException {
super(new GPConfiguration());
GPConfiguration config = getGPConfiguration();
_xVariable = Variable.create(config, "X", CommandGene.IntegerClass);
_yVariable = Variable.create(config, "Y", CommandGene.IntegerClass);
config.setGPFitnessEvaluator(new DeltaGPFitnessEvaluator());
config.setMaxInitDepth(4);
config.setPopulationSize(1000);
config.setMaxCrossoverDepth(8);
config.setFitnessFunction(new SimpleMathTestFitnessFunction(INPUT_1, INPUT_2, OUTPUT, _xVariable, _yVariable));
config.setStrictProgramCreation(true);
}
@Override
public GPGenotype create() throws InvalidConfigurationException {
GPConfiguration config = getGPConfiguration();
// The return type of the GP program.
Class[] types = { CommandGene.IntegerClass };
// Arguments of result-producing chromosome: none
Class[][] argTypes = { {} };
// Next, we define the set of available GP commands and terminals to
// use.
CommandGene[][] nodeSets = {
{
_xVariable,
_yVariable,
new Add(config, CommandGene.IntegerClass),
new Multiply(config, CommandGene.IntegerClass),
new Terminal(config, CommandGene.IntegerClass, 0.0, 10.0, true)
}
};
GPGenotype result = GPGenotype.randomInitialGenotype(config, types, argTypes,
nodeSets, 20, true);
return result;
}
public static void main(String[] args) throws Exception {
GPProblem problem = new SimpleMathTest();
GPGenotype gp = problem.create();
gp.setVerboseOutput(true);
gp.evolve(30);
System.out.println("Formula to discover: x^2 + 2y + 3x + 5");
gp.outputSolution(gp.getAllTimeBest());
}
}
(And remember: I don’t warrant any of the above code to do anything but crash. Please do not use it for anything at all except as examples of using the JGAP framework. Especially don’t use the above code in nuclear submarines, nuclear power plants or Cylons. Okay, maybe Cylons.)
Yeah, Java is more verbose. We really need to do something about that.
Much thanks to Toby Segaran for his lucid explanation of GP principles and to the JGAP team for what appears to be an awesome framework.