Archive
Help! I Programmatically Created a Resource in my Project, but My Code Doesn’t Find It!
Let’s say that you wanted to test the existence of a file you programmatically created in your project. While there are a lot of situations where you might create an IResource on the fly, creating a file for use in a test is not a bad example.
The test code could look like this (TestUtilities is a convenience class that does things for me):
...
import org.junit.Assert;
...
@Test
public void testFileExistsTrue() throws IOException, CoreException {
_project = TestUtilities.createProject("x"); //$NON-NLS-1$
TestUtilities.createTemplateFileInProjectAt(_project, CustomSchemaSupport.SCHEMA_FOLDER_NAME, CustomSchemaSupport.FILENAME);
boolean actual = _customSchemaSupport.fileExists(_project);
try {
Assert.assertTrue(actual);
} finally {
// always do this before returning
_project.delete(true, null);
}
}
Writing an Eclipse Plug-in (Part 15): Custom Project: Customizing the Perspective Menus (Main menu)
Ah! Nothing like returning to the scene of the crime.
When we were last at the crime scene we were displaying projects in the Custom Navigator in various states of openness and closedness. What could possibly be next? Well, there are a few choices:
- Customize the Custom Perspective so our current capabilities are available in the main workspace menu, toolbar and Customize Perspective window.
- Add navigator popup menus to do things like New, Copy and Properties
- Display information in the project structure
Even though I expect to create a Form-based editor to hide the ugliness of an XML file that is not necessarily the task of greatest import. In this post I am going to show how to add menu items to our Custom Perspective; we will customize the Custom Navigator popup menu in a future post.
We should always be implementing with the end in mind as a way of keeping extraneous features to a minimum anyway. At least that’s my story.
What (are we doing?)
There are about 7 ways to do almost anything in Eclipse. For example, if you want to open the New Wizard you could go about doing that in the following ways:
- Ctrl+N
- Main menu: File –> New
- Shift+Alt+N – opens the popup menu; select New
- Right click on a Project and select New
- Right click on a Folder and select New
- Toolbar: New button
- Toolbar: Java Class button: New: JUnit Test, Class, Interface, Enum, Annotation
And those were just the ones I thought of off the top of my head (okay, so maybe I tried them all first…).
So, in order to compete with all of the other plug-ins out there a plug-in developer has to make sure there are at least a minimum of ways to activate their plug-in: CRUD functionality (New, Open, Save, Delete), opening editor(s) and view(s), open the Properties window, etc.
The good news: Ctrl+N and Shift+Alt+N open the New Wizard window in every case (unless you change the key bindings) so we can safely ignore them.
The bad news: we only have a New Wizard for Custom Projects and two file types. This means that the only way to create a custom resource is either from the main menu (File –> New –> Other), Ctrl+N, or Shift+Alt+N. Since all three will activate the default New Wizard we have not gained anything.
The lesson to learn here is when you add something to the New Wizard your task list should include updating your perspective to support the:
- Main Menu File menu
- Toolbar
- Customize Perspective window
Notice how the only thing this will do is make your existing behavior available in more places. Not a bad thing, just kinda extraneous; convenient for the user, feels like busy work for the developer.
You could also decide to add your GUI functionality to all of the perspectives, but beware: each perspective is specific to the task at hand. Adding the ability to do random things in arbitrary perspectives is bad form. Add functionality to specific perspectives as appropriate (what that means will vary with the capability you are implementing). Adding plugin.xml to a COBOL project doesn’t really mean anything. The road to menu pollution is paved with good intentions. Don’t be afraid to create custom perspectives where you can just go to town adding whatever you want with impunity.
So the tasks for the next few blogs are to add:
- In the main menu: add Custom Projects, Schema, and Deployment files to File –> New
- In the Toolbar: add a toolbar group for the above 3 items
- In Customize Perspective: add the ability to enable/disable all of the above
In the Customize Perspective window adding the ability to enable/disable the above capabilities means:
- Toolbar Visibility: Custom Project Element Creation (enable by default)
- Custom Project
- Schema File
- Deployment File
- Menu Visibility: File –> New, (already available, enable by default)
- Custom Project
- Schema File
- Deployment File
- Command Group Availability: Custom Project Element Creation (enable by default)
- Shortcuts (affects Menu Visibility; enable by default)
- New
- Custom Project
- Schema File
- Deployment File
- Open Perspective (Affects main menu Windows –> Open Perspective)
- Resource (available, but not enabled)
- Show View (Affects main menu Windows –> Open View)
- Custom Plug-in Navigator (available, but not enabled)
- New
How (are we doing it?)
In the main menu: add Custom Projects, Schema, and Deployment files to File –> New
Adding New Wizard entries onto the menu menu is done completely by configuration (my favorite).
- Open up plugin.xml for customplugin
- Go to Extensions–> Add –> perspectiveExtension and click Finish (yes, you could skip this step and use the existing perspectiveExtension entry)
- Change
- targetID: *
to
- targetID: customplugin.perspective
- Right click on customplugin.perspective (perspectiveExtension) –> new –> newWizardShortcut
- Select newWizardShortcut and enter:
- ID: customplugin.wizard.new.custom
- The above is the id of the New Custom Project Wizard entry under org.eclipse.ui,newWizards –> Custom Project (wizard)
- Perform steps 4 and 5 for the Schema File (wizard) and Deployment File (wizard)
- Save plugin.xml
To make them appear in all of the perspectives change (do not try this at home. I am a trained professional):
- Extensions –> perspectiveExtension –> targetID: customplugin.perspective
to
- Extensions –> perspectiveExtension –> targetID: *
Remember, only you can prevent menu pollution.
As a wonderful side-effect the Customize Perspective window has the three New wizard entries entered automatically. Start the runtime workbench, open the Customize Perspective window (Windows –> Customize Perspective), select Menu Visibility and open File –> New.
In addition select the Shortcuts tab of the Customize Perspective window and see that for Submenu New the Shortcut Category has Custom Wizards selected and the three wizards are already checked.
The Toolbar tab and the Command Groups Availability tab are both devoid of entries for our Custom Project. Are we going to take care of that now? Well…no. Next time. Really. I know you’re disappointed, but if you push me I’ll make sure you get a lump of coal.
What Just Happened?
Configuration. Nothing like it for tedious tasks.
How much code did we write: none. It is going to be a good holiday.
Well, that’s it for this entry. It is Sunday, the holidays are getting closer and I was lucky to get this post out.
Next time: Adding the New Wizard functionality to the Toolbar. Maybe. If I get a Sega R-360.
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>


