Skip to main content

Notice: this Wiki will be going read only early in 2024 and edits will no longer be possible. Please see: https://gitlab.eclipse.org/eclipsefdn/helpdesk/-/wikis/Wiki-shutdown-plan for the plan.

Jump to: navigation, search

Difference between revisions of "SWTBot/UsersGuide"

(Configuration)
m (Recorder and Generator: should be a main heading so that it don't end up under GEF in the TOC.)
(31 intermediate revisions by 13 users not shown)
Line 1: Line 1:
 +
{{SWTBot}}
 +
 
=SWTBot Users Guide=
 
=SWTBot Users Guide=
 +
 +
Information on this page may be outdated.
 +
 +
Note that this page is for first time users. {{SWTBotLink|AdvancedUsers|Advanced Users}} click here.
 +
 
==Introduction==
 
==Introduction==
  
Line 10: Line 17:
 
SWTBot can run on all platforms that SWT runs on. Very few other testing tools provide such a wide variety of platforms.
 
SWTBot can run on all platforms that SWT runs on. Very few other testing tools provide such a wide variety of platforms.
 
==Quick Start==
 
==Quick Start==
===Configuration===
 
  
SWTBot comes with a releng project and things generally work out of the box. The build instructions are available in the readme in the releng project.
+
=== A Screencast ===
  
There are dependencies on org.hamcrest and com.thoughtworks. These are not checked into the SWTBot repository and nor are they in orbit yet.
+
Videos speak louder than pictures and words put together:
 +
* [http://download.eclipse.org/technology/swtbot/docs/videos/beginners/SWTBotGettingStartedIn5Minutes A 5 minute quick quick tutorial on how to get started with swtbot]
 +
* [http://download.eclipse.org/technology/swtbot/docs/videos/beginners/SWTBotHeadlessTestingForNovices Running SWTBot tests from the command line]
  
You can download the dependencies from https://swtbot.svn.sourceforge.net/svnroot/swtbot/branches/java-1.5-api-spike/org.eclipse.swtbot.releng/externals/plugins/ for now (and put them in .releng/externals/plugins)
+
=== Creating A Project ===
  
A patched version of the eclipse test framework is available at https://swtbot.svn.sourceforge.net/svnroot/swtbot/branches/java-1.5-api-spike/org.eclipse.swtbot.releng/test-sandbox/eclipse-test-framework-3.3.zip (you'll need to put this into .releng/externals)
+
Create a new project by clicking on '''File>New>Project'''. On the '''New Project Dialog''', search for "plug-in", select '''New Plug-in Project''' and click '''Next'''. Create a new plugin project named '''org.eclipsecon.swtbot.example'''.
  
 +
[[Image:Swtbot-create-project.gif]]
 +
 +
===Configuration===
  
 
* Add the following to your classpath:
 
* Add the following to your classpath:
   org.eclipse.swtbot.finder
+
   org.eclipse.swtbot.eclipse.finder
 +
  org.eclipse.swtbot.junit4_x
 +
  org.hamcrest.core
 
   org.apache.commons.collections
 
   org.apache.commons.collections
 +
  org.junit4
 
   org.apache.log4j
 
   org.apache.log4j
* These are useful if you are using SWTBot to test Eclipse plugins
+
   org.eclipse.ui
   org.eclipse.swtbot.eclipse.finder
+
  
===Installation from the GIT Repository===
+
[[Image:Swtbot-setup-dependencies.gif]]
  
If you expect to be making changes to the SWTBot source code then the you should consider using GIT.  The SWTBot Subversion repository is mirrored to a GIT repository.  Although GIT has a higher learning curve than Subversion, you will find it easier to manage your changes and it will be easier for others to pull your changes.
+
===Getting started with SWTBot===
  
The GIT repository is at git://github.com/ketan/swtbot.git.
+
SWTBot requires that tests run on a non-UI thread, so that '''PlatformUI.getWorkbench()''' will return you null and that traditional unit-test code won't work. If you run tests on the UI thread, they will eventually block the UI at some point in time. Take a look into the FAQ for [[SWTBot/FAQ#Why do tests run on a non-UI thread?|explanations]] and [[SWTBot/FAQ#How do I execute parts of tests that need UI thread?|workaround]].
  
If you clone this repository and import the projects into Eclipse, you will find a few errors.  These can be fixed as follows:
+
===Getting started with SWTBot for Eclipse Plugins===
  
org.eclipse.swtbot.eclipse.ui contains two versions of the .classpath file. These are named _classpath.eclipse_3.4 and _classpath.eclipse_3.5.  Copy one of these to .classpath, depending on which version of Eclipse is being used in your runtime environment.  The build errors for this plug-in should go away.  There are also two versions of the build.properties file.  You will need to copy one of these too if you are going to do PDE builds or create your own update site.
+
To use SWTBot along with your eclipse plugin application you have to add the below plugins to your dependencies. You can download the example from the swtbot download site http://download.eclipse.org/technology/swtbot/docs/eclipsecon2009/examples.zip.
 +
 
 +
Now you can start using SWTBot. Below you can find a sample SWTBot testcase:
  
org.eclipse.swtbot.junit4_x contains two versions each of .classpath and MANIFEST.MF in the META-INF directory.  Depending on the version of JUnit you are using, copy one of _classpath.junit4_3 or _classpath.junit4_5 to .classpath and in the META-INF directory copy one of MANIFEST.MF_junit4_3 or MANIFEST.MF_junit4_5 to MANIFEST.MF.  The build errors for this plug-in should go away.
+
<source lang="java">
 +
package org.eclipsecon.swtbot.example;
  
Note that the org.hamcrest and com.thoughtworks bundles are checked into the SWTBot GIT repository and can be found in the org.eclipse.swtbot.releng project in externals/plugins. So you don't have to fetch these separately as you would if using the Subversion repository at eclipse.org.
+
import org.eclipse.swtbot.eclipse.finder.SWTWorkbenchBot;
 +
import org.eclipse.swtbot.swt.finder.junit.SWTBotJunit4ClassRunner;
 +
import org.eclipse.swtbot.swt.finder.widgets.SWTBotShell;
 +
import org.junit.AfterClass;
 +
import org.junit.BeforeClass;
 +
import org.junit.Test;
 +
import org.junit.runner.RunWith;
  
===Getting started with SWTBot===
+
@RunWith(SWTBotJunit4ClassRunner.class)
 +
public class MyFirstTest {
  
SWTBot requires that tests run on a non-UI thread. If you run tests on the UI thread, they will eventually block the UI at some point in time. More info on this behavior available in the [[SWTBot/FAQ|FAQ]].
+
private static SWTWorkbenchBot bot;
  
===Getting started with SWTBot for SWT applications===
+
@BeforeClass
 +
public static void beforeClass() throws Exception {
 +
bot = new SWTWorkbenchBot();
 +
bot.viewByTitle("Welcome").close();
 +
}
  
Because SWTBot tests need to [[SWTBot/FAQ#Why_do_tests_run_on_a_non-UI_thread.3F|run in a non-UI thread]], it is essential that the application starts off in another thread. The example below uses a simple mechanism to start the tests in another thread. You could use any other mechanism to do this instead.
 
  
<source lang="java">
+
@Test
import net.sf.swtbot.SWTBotTestCase;
+
public void canCreateANewJavaProject() throws Exception {
import net.sf.swtbot.utils.SWTUtils;
+
bot.menu("File").menu("New").menu("Project...").click();
import net.sf.swtbot.widgets.TimeoutException;
+
  
import org.eclipse.swt.widgets.Display;
+
SWTBotShell shell = bot.shell("New Project");
 +
shell.activate();
 +
bot.tree().expandNode("Java").select("Java Project");
 +
bot.button("Next >").click();
  
public class FooBarTest extends SWTBotTestCase {
+
bot.textWithLabel("Project name:").setText("MyFirstProject");
  
  // pull this up into your own superclass that extends SWTBotTestCase and extend from your superclass instead
+
bot.button("Finish").click();
  static {
+
// FIXME: assert that the project is actually created, for later
    startApplicationInAnotherThread();
+
}
  }
+
  
  protected void setUp() throws Exception {
+
@AfterClass
    super.setUp();
+
public static void sleep() {
    waitForDisplayToAppear(5000); // wait for the display to appear before you do anything
+
bot.sleep(2000);
  }
+
}
  
  public void testClicksOnAButton() throws Exception {
+
}
    bot.button("click me").click();
+
</source>
    bot.button("you just clicked me!").click();
+
  }
+
  
  public void testThisFails() throws Exception {
+
===Executing SWTBot Tests for Eclipse Plugins===
    bot.button("this does not exist").click();
+
  }
+
  
  private void waitForDisplayToAppear(long timeOut) throws TimeoutException, InterruptedException {
+
Now that you've written the great test that you'd always wanted to, lets now see it run. In order to run the test, right click on the test and select '''Run As > SWTBot Test'''
    long endTime = System.currentTimeMillis() + timeOut;
+
    while (System.currentTimeMillis() < endTime) { // wait until timeout
+
      try {
+
        Display display = SWTUtils.display();
+
        if (display != null)
+
          return;
+
      } catch (Exception e) {
+
        // did not find a display? no problems, try again
+
      }
+
      Thread.sleep(100); // sleep for a while and try again
+
    }
+
    throw new TimeoutException("timed out");
+
  }
+
  
  private static void startApplicationInAnotherThread() {
+
[[Image:run-as-option.jpg]]
    new Thread(new Runnable() {
+
      public void run() {
+
        new MyApplication().main(new String[] { "some", "command", "line", "arguments for your application" });
+
      }
+
    }).start();
+
  }
+
  
}
+
Select the application that you want to test
</source>
+
  
===Getting started with SWTBot for Eclipse Plugins===
+
[[Image:run-as-config-options.jpg]]
  
To use SWTBot along with your eclipse plugin application you have to add the below plugins to your dependencies.
+
= GEF/GMF-based editor testing =
 
+
  org.eclipse.swtbot.swt.finder
+
  org.eclipse.swtbot.eclipse.finder
+
  org.junit4
+
  
Now you can start using SWTBot. Below you can find a sample SWTBot testcase:
+
== Intro ==
  
<source lang="java">
+
SWT has a plugin that allows to manipulate GEF/GMF diagrams, editors and editParts as easily as you can manipulate SWT widgets with SWTBot. Then you can easily create some repeatable user-level UI interations and check their effects on the diagram
import junit.framework.TestCase;
+
  
import org.eclipse.swtbot.eclipse.finder.SWTEclipseBot;
+
== Configuration ==
import org.eclipse.swtbot.swt.finder.exceptions.WidgetNotFoundException;
+
import org.eclipse.swtbot.swt.finder.widgets.SWTBotTree;
+
  
/**
+
The configuration is similar to the one describe before for SWTBot, except that you also have to add '''org.eclipse.swtbot.eclipse.gef.finder''' plugin and some other dependencies, such as '''org.eclipse.ui'''. In most case, you'll also like to use GEF and/or GMF plugins to make some checks on diagram.
*
+
* This is a sample swtbot testcase for an eclipse application.
+
*
+
*/
+
public class TestSampleDialog extends TestCase {
+
  
  /**
+
== Getting started with examples ==
  * In future you will not need to create this instance.
+
  * You need to extend SWTBotEclipseTestCase which holds an instance of
+
  * SWTEclipseBot.
+
  */
+
  protected SWTEclipseBot bot = new SWTEclipseBot();
+
  
  /**
+
If you like to get started with working examples, you can take a look at the following URL, or [[SWTBot/Contributing#Getting the source | check them out]] in your workspace.
  * This testcase will create a new java project in  
+
  * your workspace.
+
  */
+
  public void testCreateJavaProject() {
+
  
    try {
+
Example GEF project: http://git.eclipse.org/c/swtbot/org.eclipse.swtbot.git/tree/examples/gef/org.eclipse.gef.examples.logic
      bot.view("Welcome").close() ;
+
<br/>
    } catch (WidgetNotFoundException e) {
+
Example SWTBot for GEF test case: http://git.eclipse.org/c/swtbot/org.eclipse.swtbot.git/tree/examples/gef/org.eclipse.gef.examples.logic.test
      fail("Welcome window not found.");
+
    }
+
   
+
    //This will open the the menu File > New > Project wizard
+
    bot.menu("File").menu("New").menu("Project...").click();
+
    bot.sleep(1000);
+
   
+
    //Select the java project from the wizard tree.
+
    SWTBotTree projectSelectionTree = bot.tree();
+
    projectSelectionTree.select("Java Project");
+
    bot.sleep(1000);
+
   
+
    //Click Next button
+
    bot.button("Next >").click();
+
    bot.sleep(1000);
+
   
+
    //'com.swtbot.test.project' is the java project name to create
+
    bot.textWithLabel("Project name:").setText("com.swtbot.test.project");
+
    bot.sleep(1000);
+
   
+
    //Click the Finish button
+
    bot.button("Finish").click();
+
    bot.sleep(1000);
+
   
+
    //Now the project is created in your workspace.
+
  }
+
 
+
  /**
+
  * This testcase will set the focus on a view.
+
  */
+
  public void testFocusView() {
+
    try {
+
      bot.view("Welcome").close() ;
+
    } catch (WidgetNotFoundException e) {
+
      fail("Welcome window not found.");
+
    }
+
  
    //This will set focus on the Problems view
+
== General principles ==
    //The view is identified using the title of the view.
+
    bot.view("Problems").setFocus();
+
  
    //The sleep command can be used to slow down the testcase
+
Everything is almost the same as using SWTBot, except that some classes change in order to give you the ability to manipulate DiagramEditors. The SWTBotTestCase superclass must be replaced by '''SWTBotGefTestCase'''. From the inside of your SWTBotTestCase, you can access your '''SWTGefBot''' ''bot'' field to play with your GEF editor. Then you retrieve a '''SWTBotGefEditor''' by using ''bot.getEditor("label of my editor tab")''.
    //execution so that you can see it or you can wait for a
+
    //background process to complete.
+
    bot.sleep(2000);
+
  }
+
}
+
</source>
+
  
You can find one more SWTBot Testcase snippet below,
+
Once you have your SWTBotGefEditor, you can perform high level user operations programatically:
  
 +
=== Creation of elements ===
 
<source lang="java">
 
<source lang="java">
// subclassing SWTBotTestCase gives you an instance of
+
// retrieve editor
// SWTBot that offers a lot of convinience api
+
SWTBotGefEditor editor = bot.gefEditor("test.logic"); // editor must be already open
// this class also has a lot of assertions that are suited for ui operations
+
// Simulate creation of element from palette
public class FooTest extends SWTBotEclipseTestCase {
+
editor.activateTool("Circuit");  // "Circuit" is the label of the tool in palette
+
editor.mouseDrag(55, 55, 150, 100);
  // stuff you can do with Eclipse
+
editor.activateTool("Circuit");
  public void testDoSomethingInterestingWithEclipse() throws Exception {
+
editor.mouseMoveLeftClick(150, 150);
    bot.view("Package Explorer").close();
+
editor.activateTool("Connection");
    bot.editor("HelloWorld.java").save();
+
editor.mouseMoveLeftClick(150, 150);
    bot.editor("FooBar.java").close();
+
editor.mouseMoveLeftClick(55, 55);
+
    bot.activeEditor().typeText("public static void main ()...");
+
    bot.activeEditor().quickfix("Rename in file");
+
+
    // will insert "System.out.println();" in the currently open editor
+
    bot.activeEditor().autoCompleteProposal("sys", "sysout - print to standard out");
+
  }
+
   
+
  // stuff you can do with SWT
+
  public void testDoSomethingInterestingWithSWT() throws Exception {
+
+
    // there are two parts to SWTBot:
+
    // one to find a control (the subject)
+
    // and the action to be performed on the control (the verb)
+
    bot.shell("Address Book - Untitled").activate();
+
    bot.button("Hello World").click();
+
    bot.menu("File").menu("New").click();
+
    bot.captureScreenshot("myscreenshot.png");
+
+
    bot.listWithLabel("My Items").select(new String[] { "foo", "bar", "baz" });
+
+
    // there are a lot of assertions that are very useful
+
    assertEnabled(bot.button("Foo Bar"));
+
    assertVisible(bot.checkBox("This should not visible"));
+
    assertTextContains("I just love this!", bot.textWithLabel("Comments"));
+
  }
+
}
+
 
</source>
 
</source>
  
===Executing SWTBot Tests for Eclipse Plugins===
+
=== Direct edition of editParts ===
  
Now that you've written the great test that you'd always wanted to, lets now see it run. In order to run the test, right click on the test and select Run As > Run Configurations...
+
<source lang="java">
 +
SWTBotGefEditPart editPart = editor.getEditPart("edit part label"); // select edit part by label
 +
editPart.click();
 +
editor.directEditType("new edit part label");
 +
</source>
  
[[Image:run-as-option.jpg]]
+
=== Perform a drag'n'drop ===
  
 +
<source lang="java">
 +
editor.mouseDrag(fromXPosition, fromYPosition, toXPosition, toYPosition)
 +
</source>
  
Create a new test under SWTBot Test. Ensure that you're using JUnit 3
+
=== Mix it with GEF/GMF to perform checks ===
  
[[Image:run-as-config-create.jpg]]
+
TODO: create an example that ensure that creation of a specific element is not possible on mainEditPart
  
 +
= Recorder and Generator =
  
Select the application that you want to test
+
SWTBot comes with a tool that generates some code based on events performed at runtime. It makes writing tests easier and faster. See [[SWTBot/Generator]].
 
+
[[Image:run-as-config-options.jpg]]
+
  
[[Category:SWTBot]]
+
[[Category:Draft Documentation]] [[Category:SWTBot]]

Revision as of 08:30, 17 October 2013


SWTBot
Website
Update Sites
Community
Mailing List
Forums/Newsgroups
IRC
Contribute
Open Bugzilla tickets
Open Gerrit reviews
Browse Source
Continuous Integration


SWTBot Users Guide

Information on this page may be outdated.

Note that this page is for first time users. Advanced Users click here.

Introduction

SWTBot is an open-source Java based functional testing tool for testing SWT and Eclipse based applications.

SWTBot provides APIs that are simple to read and write. The APIs also hide the complexities involved with SWT and Eclipse. This makes it suitable for functional testing by everyone. SWTBot also provides its own set of assertions that are useful for SWT. You can also use your own assertion framework with SWTBot.

SWTBot can record and playback tests and integrates with Eclipse, and also provides for ant tasks so that you can run your builds from within CruiseControl or any other CI tool that you use.

SWTBot can run on all platforms that SWT runs on. Very few other testing tools provide such a wide variety of platforms.

Quick Start

A Screencast

Videos speak louder than pictures and words put together:

Creating A Project

Create a new project by clicking on File>New>Project. On the New Project Dialog, search for "plug-in", select New Plug-in Project and click Next. Create a new plugin project named org.eclipsecon.swtbot.example.

Swtbot-create-project.gif

Configuration

  • Add the following to your classpath:
  org.eclipse.swtbot.eclipse.finder
  org.eclipse.swtbot.junit4_x
  org.hamcrest.core
  org.apache.commons.collections
  org.junit4
  org.apache.log4j
  org.eclipse.ui

Swtbot-setup-dependencies.gif

Getting started with SWTBot

SWTBot requires that tests run on a non-UI thread, so that PlatformUI.getWorkbench() will return you null and that traditional unit-test code won't work. If you run tests on the UI thread, they will eventually block the UI at some point in time. Take a look into the FAQ for explanations and workaround.

Getting started with SWTBot for Eclipse Plugins

To use SWTBot along with your eclipse plugin application you have to add the below plugins to your dependencies. You can download the example from the swtbot download site http://download.eclipse.org/technology/swtbot/docs/eclipsecon2009/examples.zip.

Now you can start using SWTBot. Below you can find a sample SWTBot testcase:

package org.eclipsecon.swtbot.example;
 
import org.eclipse.swtbot.eclipse.finder.SWTWorkbenchBot;
import org.eclipse.swtbot.swt.finder.junit.SWTBotJunit4ClassRunner;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotShell;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
 
@RunWith(SWTBotJunit4ClassRunner.class)
public class MyFirstTest {
 
	private static SWTWorkbenchBot	bot;
 
	@BeforeClass
	public static void beforeClass() throws Exception {
		bot = new SWTWorkbenchBot();
		bot.viewByTitle("Welcome").close();
	}
 
 
	@Test
	public void canCreateANewJavaProject() throws Exception {
		bot.menu("File").menu("New").menu("Project...").click();
 
		SWTBotShell shell = bot.shell("New Project");
		shell.activate();
		bot.tree().expandNode("Java").select("Java Project");
		bot.button("Next >").click();
 
		bot.textWithLabel("Project name:").setText("MyFirstProject");
 
		bot.button("Finish").click();
		// FIXME: assert that the project is actually created, for later
	}
 
 
	@AfterClass
	public static void sleep() {
		bot.sleep(2000);
	}
 
}

Executing SWTBot Tests for Eclipse Plugins

Now that you've written the great test that you'd always wanted to, lets now see it run. In order to run the test, right click on the test and select Run As > SWTBot Test

Run-as-option.jpg

Select the application that you want to test

Run-as-config-options.jpg

GEF/GMF-based editor testing

Intro

SWT has a plugin that allows to manipulate GEF/GMF diagrams, editors and editParts as easily as you can manipulate SWT widgets with SWTBot. Then you can easily create some repeatable user-level UI interations and check their effects on the diagram

Configuration

The configuration is similar to the one describe before for SWTBot, except that you also have to add org.eclipse.swtbot.eclipse.gef.finder plugin and some other dependencies, such as org.eclipse.ui. In most case, you'll also like to use GEF and/or GMF plugins to make some checks on diagram.

Getting started with examples

If you like to get started with working examples, you can take a look at the following URL, or check them out in your workspace.

Example GEF project: http://git.eclipse.org/c/swtbot/org.eclipse.swtbot.git/tree/examples/gef/org.eclipse.gef.examples.logic
Example SWTBot for GEF test case: http://git.eclipse.org/c/swtbot/org.eclipse.swtbot.git/tree/examples/gef/org.eclipse.gef.examples.logic.test

General principles

Everything is almost the same as using SWTBot, except that some classes change in order to give you the ability to manipulate DiagramEditors. The SWTBotTestCase superclass must be replaced by SWTBotGefTestCase. From the inside of your SWTBotTestCase, you can access your SWTGefBot bot field to play with your GEF editor. Then you retrieve a SWTBotGefEditor by using bot.getEditor("label of my editor tab").

Once you have your SWTBotGefEditor, you can perform high level user operations programatically:

Creation of elements

	// retrieve editor
	SWTBotGefEditor editor = bot.gefEditor("test.logic"); // editor must be already open
	// Simulate creation of element from palette
	editor.activateTool("Circuit");  // "Circuit" is the label of the tool in palette
	editor.mouseDrag(55, 55, 150, 100);
	editor.activateTool("Circuit");
	editor.mouseMoveLeftClick(150, 150);
	editor.activateTool("Connection");
	editor.mouseMoveLeftClick(150, 150);
	editor.mouseMoveLeftClick(55, 55);

Direct edition of editParts

	SWTBotGefEditPart editPart = editor.getEditPart("edit part label"); // select edit part by label
	editPart.click();
	editor.directEditType("new edit part label");

Perform a drag'n'drop

	editor.mouseDrag(fromXPosition, fromYPosition, toXPosition, toYPosition)

Mix it with GEF/GMF to perform checks

TODO: create an example that ensure that creation of a specific element is not possible on mainEditPart

Recorder and Generator

SWTBot comes with a tool that generates some code based on events performed at runtime. It makes writing tests easier and faster. See SWTBot/Generator.

Back to the top