Previous Page
Next Page

2.8. Writing Plug-in Tests

Eclipse is a continually moving target, and when building commercial plug-ins, tests are necessary to ensure that the product continues to function properly over multiple releases. If the goal was to develop and release a plug-in once, then manual testing would suffice; however, automated tests are better at preventing regressions from creeping into the product over time.

2.8.1. Test preparation

Before a test for the Favorites view can be created, you must modify the Favorites plug-in manifest so that the appropriate classes are visible to the test plug-in. Open the plug-in manifest editor by double-clicking on the plugin.xml file, then switch to the Runtime page (see Figure 2-11). In the Exported Packages section, click Add..., select the com.qualityeclipse.favorites.views package and save the changes by selecting File > Save.

Next, add the appropriate accessor so that the test can validate the view content. In the FavoritesView class, add the following method:

/**
 * For testing purposes only.
 * @return the table viewer in the Favorites view
 */
public TableViewer getFavoritesViewer() {
 return viewer;
}

Tip

You can limit the visibility of your exported packages by specifying which plug-ins can access a package in the Package Visibility section of the Runtime page in the plug-in manifest editor (see Section 20.2.5, Related plug-ins, on page 713). Alternatively, you can place tests into a fragment so that no packages need to be exported (for more on fragments, see Section 16.3, Using Fragments, on page 587).


2.8.2. Creating a Plug-in test project

Use the same procedure as outlined in Section 2.2, Creating a Plug-in Project, on page 66, to create a new plug-in project with the following exceptions:

  • Name the project com.qualityeclipse.favorites.test

  • Put favoritesTest.jar on the classpath

  • Change the plug-in class name to com.qualityeclipse.favorites.test.FavoritesTestPlugin

  • Uncheck the Create a plug-in using one of these templates checkbox

    After the project has been created, use the Dependencies page of the plug-in manifest editor (see Figure 2-10 on page 73) to add the following required plug-ins and then save the changes:

  • com.qualityeclipse.favorites

  • org.junit

2.8.3. Creating a Plug-in test

When a project has been created and the plug-in manifest modified, it's time to create a simple test for the Favorites plug-in (see the following code example). The goal of the test is to show the Favorites view, validate its content, and then hide the view.

package com.qualityeclipse.favorites.test;

import junit.framework.AssertionFailedError;
import junit.framework.TestCase;

import org.eclipse.core.runtime.Platform;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.PlatformUI;

import com.qualityeclipse.favorites.views.FavoritesView;

/**
 * The class <code>FavoritesViewTest</code> contains tests
 * for the class {@link
 *    com.qualityeclipse.favorites.views.FavoritesView}.
 *
 * @pattern JUnit Test Case
 * @generatedBy CodePro Studio
 */
public class FavoritesViewTest extends TestCase
{
   private static final String VIEW_ID =
      "com.qualityeclipse.favorites.views.FavoritesView";

   /**
    * The object that is being tested.
    *
    * @see com.qualityeclipse.favorites.views.FavoritesView
    */
   private FavoritesView testView;
   /**
    * Construct new test instance.
    *
    * @param name the test name
    */
   public FavoritesViewTest(String name) {
      super(name);
   }

   /**
    * Perform pre-test initialization.
    *
    * @throws Exception
    *
    * @see TestCase#setUp()
    */
   protected void setUp() throws Exception {
      super.setUp();
      // Initialize the test fixture for each test
      // that is run.
      waitForJobs();
      testView = (FavoritesView)
         PlatformUI
            .getWorkbench()
            .getActiveWorkbenchWindow()
            .getActivePage()
            .showView(VIEW_ID);

      // Delay for 3 seconds so that
      // the Favorites view can be seen.
      waitForJobs();
      delay(3000);

      // Add additional setup code here.
   }

   /**
    * Perform post-test cleanup.
    *
    * @throws Exception
    *
    * @see TestCase#tearDown()
    */
   protected void tearDown() throws Exception {
      super.tearDown();
      // Dispose of test fixture.
      waitForJobs();
      PlatformUI
         .getWorkbench()
         .getActiveWorkbenchWindow()
         .getActivePage()
         .hideView(testView);

      // Add additional teardown code here.
   }
   /**
    * Run the view test.
    */
   public void testView() {
      TableViewer viewer = testView.getFavoritesViewer();
      Object[] expectedContent =
         new Object[] { "One", "Two", "Three" };
      Object[] expectedLabels =
         new String[] { "One", "Two", "Three" };

      // Assert valid content.
      IStructuredContentProvider contentProvider =
         (IStructuredContentProvider)
            viewer.getContentProvider();
      assertEquals(expectedContent,
         contentProvider.getElements(viewer.getInput()));

      // Assert valid labels.
      ITableLabelProvider labelProvider =
         (ITableLabelProvider) viewer.getLabelProvider();
      for (int i = 0; i < expectedLabels.length; i++)
         assertEquals(expectedLabels[i],
            labelProvider.getColumnText(expectedContent[i], 1));
   }

   /**
    * Process UI input but do not return for the
    * specified time interval.
    *
    * @param waitTimeMillis the number of milliseconds
    */
   private void delay(long waitTimeMillis) {
      Display display = Display.getCurrent();

      // If this is the UI thread,
      // then process input.
      if (display != null) {
         long endTimeMillis =
            System.currentTimeMillis() + waitTimeMillis;
         while (System.currentTimeMillis() < endTimeMillis)
         {
            if (!display.readAndDispatch())
               display.sleep();
         }
         display.update();
      }
      // Otherwise, perform a simple sleep.
      else {
         try {
            Thread.sleep(waitTimeMillis);
         }
         catch (InterruptedException e) {
            // Ignored.
         }
      }
   }
    /**
    * Wait until all background tasks are complete.
    */
   public void waitForJobs() {
      while (Platform.getJobManager().currentJob() != null)
         delay(1000);
   }

   /**
    * Assert that the two arrays are equal.
    * Throw an AssertionException if they are not.
    *
    * @param expected first array
    * @param actual second array
    */
   private void assertEquals(Object[] expected, Object[] actual) {
      if (expected == null) {
         if (actual == null)
            return;
         throw new AssertionFailedError(
            "expected is null, but actual is not");
      }
      else {
        if (actual == null)
           throw new AssertionFailedError(
              "actual is null, but expected is not");
      }

      assertEquals(
         "expected.length "
            + expected.length
            + ", but actual.length "
            + actual.length,
         expected.length,
         actual.length);

      for (int i = 0; i < actual.length; i++)
         assertEquals(
            "expected[" + i +
               "] is not equal to actual[" +
               i + "]",
            expected[i],
            actual[i]);
   }
}

2.8.4. Running a Plug-in test

The next step after creating a test class is to configure and execute the test. Similar to creating a runtime configuration (see Section 2.6.1, Creating a configuration, on page 88), creating a test configuration involves right-clicking on the FavoritesViewTest in the Package Explorer and selecting the Run As > JUnit Plug-in Test command. This automatically builds a test configuration and executes the test. You should then see the Runtime Workbench appear, the Favorites view open, and the Runtime Workbench close. The JUnit view indicates that your test executed successfully and the Favorites view content has been validated (see Figure 2-27).

Figure 2-27. The JUnit view.


Right clicking on the FavoritesViewTest once again and selecting Run As > Run... opens the Configuration wizard (see Figure 2-28). Here you can specify whether a single test should be executed by itself or whether all tests in a project should be executed simultaneously.

Figure 2-28. The test Configuration wizard.


2.8.5. Uninstalling the Favorites plug-in

Use the following steps to delete the Favorites plug-in from the Development Workspace:

  1. Close the Favorites view.

  2. Shut down Eclipse.

  3. Delete the com.quality.favorites_1.0.0.jar file in the Eclipse plug-ins directory.

  4. Restart Eclipse. If you get an error message (see Figure 2-29) when restarting, at least one of the Favorites views was not closed when Eclipse was shut down in Step 2.

    Figure 2-29. Problems dialog when restarting Eclipse.

  5. Verify that the Favorites view is no longer available by opening the Show View dialog (see Figure 2-18) and verifying that the Quality Eclipse category is no longer present (see Figure 2-19).


Previous Page
Next Page