SWTBot/Custom Before And After Tasks for Tests

From Eclipsepedia

Jump to: navigation, search


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



There are times when you need to do something before or after every test, or some special handing when a test fails or errors. It is possible to do this with SWTBot. This page describes what you need to do.

Currently your tests would be annotated with a SWTBotJunit4ClassRunner for eclipse 3.4 or SWTBotJunit4ClassRunner for eclipse 3.5.

SWTBotJunit4ClassRunner is a runner provided by SWTBot that lets you capture screenshots after a test fails so you can diagnose tests.

You can write your own custom runner that does something else (in addition to capturing screenshots), you don't want to miss those screenshots would you :)

How does the custom runner look like?

Depending on which version of JUnit you have, you will need to extend from TestClassRunner or from BlockJUnit4ClassRunner:

There is not much of a difference between those classes apart from the name.

  public class SWTBotJunit4ClassRunner extends TestClassRunner {
 
    public SWTBotJunit4ClassRunner(Class<?> klass) throws Exception {
      super(klass);
    }
 
    public void run(RunNotifier notifier) {
      RunListener failureSpy = new ScreenshotCaptureListener();
      notifier.removeListener(failureSpy); // remove existing listeners that could be added by suite or class runners
      notifier.addListener(failureSpy);
      // add your own custom listeners here:
       RunListener customListener = new CustomListener();
      notifier.removeListener(customListener); // remove existing listeners that could be added by suite or class runners
      notifier.addListener(customListener);
      try {
        super.run(notifier);
      } finally {
        notifier.removeListener(failureSpy);
      }
    }
  }

The CustomListener class looks like this:

  public class CustomListener extends RunListener {
    // override any methods from RunListener here
    // examples are:
    // methods for each test method
    public void testStarted(Description description) throws Exception {
    }
 
    public void testFinished(Description description) throws Exception {
    }
 
    // called when a test class starts/ends
    public void testRunStarted(Description description) throws Exception {
    }
 
    public void testRunFinished(Description description) throws Exception {
    }
 
    // make sure you put these AS-IS
    public int hashCode() {
      return 31;
    }
 
    public boolean equals(Object obj) {
      if (this == obj)
        return true;
      if (obj == null)
        return false;
      if (getClass() != obj.getClass())
        return false;
      return true;
    }
  }