Showing posts with label mocking. Show all posts
Showing posts with label mocking. Show all posts

27 March 2020

TDD an Immediate Mode UI

Today I continue my experiments with test driving user interfaces. First I looked at test driving classic, fat, state based UIs like Swing or WinForms and later web component libraries like Vaadin. I need to explore different programming environments and platforms to see what is possible. In this post I want to have a look at immediate mode GUIs. An immediate mode GUI is a GUI where the event processing is directly controlled by the application. When I first read a similar sentence on Wikipedia, it did not help me at all. So what is an immediate mode GUI?

User InterfaceRetained Mode
A better question would be "what is retained mode?" Wikipedia states that retained mode is a style of API design in which the graphics library retains the complete object model of the rendering primitives to be rendered. That means that the widget, e.g. an instance of a JButton, contains all state needed to draw the button, i.e. colours, position, is the button clicked and so forth. When the button is created, or even "drawn", it is not causing the actual rendering. The GUI library decides when and how to render the widget and optimises the actual rendering. This includes double buffering, clipping or partial updates. Retained mode is the dominant style in GUI libraries, all user interfaces you have build were likely of this style.

Immediate Mode
So let's get back to Immediate mode. When using an immediate mode GUI library, the event processing is directly controlled by the application. There is no button object, there is just a Button(bounds Rectangle, text string) function which immediately draws the button with given text at the given position and size (argument bounds). The function returns true if the button was clicked. The application code must call all drawing commands required to describe the entire scene each time a new frame is displayed. This is often used in video games programming and examples of immediate mode rendering systems include Direct2D and OpenGL. If you want to know more about this mode, see this list of immediate mode gui tutorials on StackOverflow.

The (immediate mode) UI framework I am going to use is raylib, a simple and easy to use library to enjoy video games programming. See its cheat sheet for an overview of its functions. It has a simple API which hides everything regarding windowing system and environment. I am writing code in Go, so I am using raylib-go, the Golang bindings for raylib. Honestly I have no idea what I am doing. I have never used an immediate mode framework, not even heard of one before last year. In addition I know little to nothing about the Go language. Nevertheless I managed to talk my fellow crafter, Extreme Programmer and probably Vienna's longest time Go practitioner, Christian Haas into running this experiment with me. We spent one full day working on the Login Form exercise.

The first test: There is a button
import (
  "testing"
  ...
  rl "github.com/gen2brain/raylib-go/raylib"
)

func TestForm_LoginButton(t *testing.T) {
  var form login.Form
  ui := newTestingUI()

  form.Render(ui)

  if !ui.buttonCalled {
    t.Errorf("Button() was not called")
  }
}
Form is the struct containing the form's data, which is empty for now. Render is a receiver function on the form, which creates a button with no bounds and an empty text.
type Form struct{}

func (form Form) Render(ui FormUI) {
  ui.Button(rl.Rectangle{}, "")
}
To check that certain calls into raylib have been made, there is an interface FormUI between the application code and raylib. In the tests this interface is mocked to verify certain calls have been made. (In Go an interface type is defined as a set of method signatures. This is the way to achieve polymorphism.)
type testingUI struct {
  buttonCalled bool
}

func (ui *testingUI) Button(bounds rl.Rectangle, text string) bool {
  ui.buttonCalled = true
  return false
}
This follows an approach I have found as a possible TDD approach:
  • Design and write your methods separated from the actual UI.
  • TDD the elements and behaviour.
  • Mock single UI elements to verify necessary calls but do not show them.
For Swing I cannot see how this approach would be practical, but in this example with immediate mode raylib, it feels natural.

More Code
Soon the number of interactions with the UI made it necessary to add string ids to each drawing primitive. While raylib did not need them, other libaries do, so it did not feel wrong to add them. The mocked UI was growing. Here are the final pieces of code for the login button.
type testingUI struct {
  // verify if Button method has been called (mock)
  buttonCalled  map[string]bool

  // record button's text and bounds for later inspection (spy)
  buttonText    map[string]string
  buttonBounds  map[string]rl.Rectangle

  // return value of the Button method = user interaction (stub)
  buttonResults map[string]bool

  ...
}

func newTestingUI() *testingUI {
  ui := &testingUI{
    buttonCalled:  make(map[string]bool),
    buttonText:    make(map[string]string),
    buttonBounds:  make(map[string]rl.Rectangle),
    buttonResults: make(map[string]bool),
    ...
  }
  return ui
}

func (ui *testingUI) Button(id string, bounds rl.Rectangle, text string) bool {
  ui.buttonCalled[id] = true
  ui.buttonText[id] = text
  ui.buttonBounds[id] = bounds
  result := ui.buttonResults[id]
  ui.buttonResults[id] = false // reset button click after first call
  return result
}

func TestForm_LoginButton(t *testing.T) {
  var form login.Form
  ui := newTestingUI()

  form.Render(ui)

  if !ui.buttonCalled["login"] {
    t.Errorf("not found")
  }
}

func TestForm_LoginButtonText(t *testing.T) {
  var form login.Form
  ui := newTestingUI()

  form.Render(ui)

  if "Log in" != ui.buttonText["login"] {
    t.Errorf("is not \"Log in\"")
  }
}

func TestForm_LoginButtonBounds(t *testing.T) {
  var form login.Form
  ui := newTestingUI()

  form.Render(ui)

  expectedBounds := rl.Rectangle{300, 165, 110, 30}
  if ui.buttonBounds["login"] != expectedBounds {
    t.Errorf("expected %v, but was %v", expectedBounds, ui.buttonBounds)
  }
}
and the production code
type FormUI interface {
  Button(id string, bounds rl.Rectangle, text string) bool
  ...
}

func (form *Form) Render(ui FormUI) bool {
  buttonBounds := rl.Rectangle{X: 300, Y: 165, Width: 110, Height: 30}
  if ui.Button("login", buttonBounds, "Log in") {
    // TODO authenticate
  }

  return false
}
The third test, TestForm_LoginButtonBounds checks the position and size of the button. These properties are considered "layout". I do not like to test layout. I had to open GIMP to decide on the proper rectangle in expectedBounds, which I really dislike. I also expect this values to change a lot during initial development. Additionally Rectangle is a raylib type and so we depend on raylib in our code. Other options would have been:
  • Ignore layout completely. But then we would need to revisit all calls and add the Rectangles later.
  • Use abstract coordinates, i.e. map my coordinates into raylib Rectangles. That seemed like an extra overhead.
  • Move the responsibility of layout into the wrapper. There would be a button method for each button in the application and there would be more code outside my tests.
  • Move out the bounds and store them in the wrapper with a simple lookup on the id. Moving out stuff is against the nature of Immediate mode because the whole UI is expected to be in the code.
The wrapper for raylib is straight forward.
type RaylibFormUI struct{}

func (ui *RaylibFormUI) Button(id string, bounds rl.Rectangle, text string) bool {
  return raygui.Button(bounds, text)
}
This should give you an idea how things worked out. If you want to follow our TDD steps, here are the individual commits.

Is this MVP?
The MVP (Model View Presenter pattern) has a very thin, dumb UI, which is called the view. The model contains the UI data or UI model which might contain information about enabled fields, active buttons and so on. The presenter is a mediator and wires the model and the view. In the Go code above, the Form structure could be seen as an UI model. Later it will hold the user name and password data. The form receiver function func (form *Form) Render(ui FormUI) bool contains the presenter logic. It is not a separate object - there are no objects in Go - but it could be separate. Due to the immediate mode UI, there are no callbacks from the view in case of events. This removes the need for the usual MVP event listeners. The FormUI interface is like a MVP view as it hides the raylib dependency. It does not abstract away the underlying library, it is just a thin wrapper. It is not a MVP view. It could be made a view, i.e. provide more abstract functions in domain language, and then it would need tests on its own. In the experiment, this seemed unnecessary. In the end the FormUI will delegate many functions to raylib, so it could be generated from its original source code. This shows the tight coupling of the FormUI and the underlying UI library.

Water PressureConclusion
We built a login user interface following the requirements using Test Driven Development. It was easy and we did not face any problems, so no big deal. The Immediate mode library made it easier than for retained mode: There was no need to search for components, capture events, trigger events and so forth, definitely easier than my initial experiment. When comparing these experiments for Swing and raylib, I am reminded of the difference of Classic and Mockist TDD. In retained mode, e.g. Swing, I kept checking the state of UI components while in immediate mode I verified expected calls of the library. This approach allows variable depth of checks. We could have asserted colours and styles and we did not. So we will have to look at the finished form in the end. Christian proposed saving the image of the final view and storing it for regression testing.

We used TDD but there was little pressure on the design of the code. There was some pressure on the design of the API of Form, but there was no pressure on its internal workings nor on FormUI at all. The tests drove the creation of the UI - which was dictated by the requirements - there was no space for evolution. A different (UI) design might have been easier to test, but that was not an option. (A different UI would not have been different to test in this example anyway.) So we lost this particular benefit of TDD.

Try it yourself
I will continue my experiments and I would like to hear your ideas on the topic. The Go starting code with raylib-Go, its required dependencies and linter setup is available in the Login Form Kata. Try it yourself!

16 July 2013

Word Wrap Kata revisited

Last year in November, my old post about Word Wrap Kata variants suddenly got a lot of visits. Claus told me that well known German blogger Ralf Westphal had linked to it from one of his own articles about Test Driven Development. By using examples from Coding Dojos he explained that using Test Driven Development alone is not enough to get clean code. During the Dojo the participants focused only on the red and green bars and other concerns like design or code readability were neglected. He used my code as examples of solutions got by such a behaviour. While it made me unhappy to serve as negative example, I had to agree with Ralf. When I performed the katas two years ago I explored different algorithms and did not use them to practice TDD. My solutions were technical, instead of reflecting the problem domain.

Try Harder in Your New DreamWhen I attended a Coding Dojo afterwards I paid close attention and was sad to see he that all Ralf's concerns came true. The group did not even understand the requirements completely, when people already started proposing language features and libraries which would solve the problem quickly. Solve which problem quickly? We should think about the problem first and then create code driven by our tests that is clean, readable and open for future change. Ralf had some ideas how to improve these issues behind programming. Obviously code needs to have many qualities beyond its simple correctness.

So I tried again. I got help from my friend Thomas Sundberg and we worked five remote pairing sessions on the Word Wrap code kata. We performed the kata in the "usual" way, without much thought up front and being driven by our tests. Similar to a Coderetreat, we chose additional constraints: We focused on business related names, SRP and Tell, don't ask. As a kata is a learning exercise, we took everything to the extreme. We literally spent hours discussing if a particular name was reflecting the problem domain, renaming it three times or more until we were satisfied. And we spent at least six pomodoros entirely on refactoring and cleaning up. Probably we could still improve it but we grew tired of the exercise and switched to another kata.

When I see the code now, it looks a bit weird, likely because taking "Tell, don't ask" to the extreme means never asking for any state. So the first thing we need is a class that receives the wrapped output, as we cannot ask for it. Word Wrap is an algorithm inside a word processor when a paragraph of text, which does not contain any newlines, is rendered to a page where it needs to be broken into lines of proper length:
interface Page {
    void renderLine(String lineOfProperLength);
}
In breaking the paragraph into lines of proper length, we see several responsibilities: splitting the paragraph,
interface ParagraphSplitter {
    void wrap(String paragraph);
}
which breaks the stream of text down into words, accumulating the words into lines of proper length,
interface LineAccumulator {
    void addAndHyphenateIfNeeded(String word);
    void addWithoutHyphenation(String part);
    void addCarriageReturn();
}
and maybe a hyphenation rule to determine if a word which is too long can be broken into shorter pieces,
interface HyphenationRule {
    void doHyphenate(String word, LineAccumulator lineAccumulator);
}
We did not start with this design but arrived at it when removing duplication and multiple responsibilities mercilessly ;-) The obvious implementation of ParagraphSplitter is to split on each blank, e.g.
class SeparateWordsOnBlanks implements ParagraphSplitter {

    private final LineAccumulator accumulator;

    // constructor omitted

    public void wrap(String paragraph) {
        for (String word : paragraph.split(BLANK)) {
            accumulator.addAndHyphenateIfNeeded(word);
        }
        accumulator.addCarriageReturn();
    }
}
which is not exciting at all. The heavy lifting is done by the accumulator which checks if adding the current word would exceed the maximum line length, invokes the hyphenation and adds blanks where needed. Whenever a line is complete it is rendered to the page.
class LineLengthAccumulator implements LineAccumulator {

    private final Page page;
    private final HyphenationRule hyphenation;
    private final int maximumLineLength;
    private StringBuilder currentLine = new StringBuilder();

    // constructor omitted

    public void addAndHyphenateIfNeeded(String word) {
        if (exceedingMaximumLineLength(SPACE, word)) {
            hyphenation.doHyphenate(word, this);
            return;
        }
        insertSpaceIfNeeded();
        appendToCurrentLine(word);
    }

    public void addWithoutHyphenation(String part) {
        if (exceedingMaximumLineLength(EMPTY, part)) {
            addCarriageReturn();
        }
        appendToCurrentLine(part);
    }

    private boolean exceedingMaximumLineLength(String separator, String word) {
        return currentLine.length() + separator.length() + word.length() > maximumLineLength;
    }

    public void addCarriageReturn() {
        if (currentLineHasWords()) {
            renderCurrentLine();
            lineFeed();
        }
    }

    // some private methods omitted

}
There are a bunch of unit tests using a NoneHyphenationRule or different anonymous mock rules to drive the functionality of the LineLengthAccumulator. For example
@Test
public void shouldNotWrap() {
    Page mockOutput = mock(Page.class);

    LineAccumulator accumulator = new LineLengthAccumulator(mockOutput, 78);
    accumulator.addAndHyphenateIfNeeded("This");
    accumulator.addAndHyphenateIfNeeded("is");
    accumulator.addCarriageReturn();

    verify(mockOutput).renderLine("This is");
    verify(mockOutput, times(1)).renderLine(anyString());
}
The HyphenationRule needs to know its accumulator and the other way round, which creates a conceptual cycle. Additionally we need a second method addWithoutHyphenation in the LineAccumulator to avoid endless loops during hyphenation. This is the result of following "Tell, don't ask" to the letter. Maybe HyphenationRule would be better off just returning the hyphenated word.
class SplitOnCamelCase implements HyphenationRule {

    public void doHyphenate(String word, LineAccumulator lineAccumulator) {
        if (foundAnUpperCaseLetterIn(word)) {
            String remainingWords = splitFirstSyllableFrom(word, lineAccumulator);
            doHyphenate(remainingWords, lineAccumulator);
        } else {
            lineAccumulator.addWithoutHyphenation(word);
        }
    }

    // private methods omitted
}
To unit test the hyphenation rules, a mock accumulator is used to verify the proper syllables.
@Test
public void shouldHyphenateWords() {
    LineAccumulator mockAccumulator = mock(LineAccumulator.class);
    HyphenationRule strategy = new SplitOnCamelCase();

    strategy.doHyphenate("ShortWord", mockAccumulator);

    InOrder inOrder = inOrder(mockAccumulator);
    inOrder.verify(mockAccumulator).addWithoutHyphenation("Short");
    inOrder.verify(mockAccumulator).addWithoutHyphenation("Word");
    verify(mockAccumulator, times(2)).addWithoutHyphenation(anyString());
}
I am pleased with our result, although it took us too long to complete it, which is a sign how much practice we still need ;-) See its full source code here. You might still find one or another thing that is not optimal and never will be but in comparison with my first version this Word Wrap expresses its problem domain more clearly and is easy to understand even without digging down into all the details.

18 June 2013

TDD Exam Questions

Last year I ran a three day in-house training on unit-testing and TDD using Eclipse. I wanted the course to be as interactive as possible to keep the attendees engaged all the time. Besides my slides I carried out exercises like Jason Gorman's TDD from Hell and played short movies to keep the content varied. At the end of each chapter I showed a slide with a few questions about the topic just covered. These questions gave the audience a break to recall the content just studied and reflect on it before moving on. I searched for such questions but did not find any, so I had to come up with my own.

These are my sanity-check questions. They are not complicated or long-winded, just simple questions to verify if the content was understood. Some questions also served as a base for further discussion. The developers in the audience were exposed to TDD for the very first time, so I kept them simple. If you are a seasoned developer I am sure these questions will not challenge you at all.

Writing ExamsUnit Testing with JUnit
  • What is a test fixture?
  • Which assert is used to compare the values of objects?
  • What about assertTrue(true);?
  • What about assertTrue(a.equals(b));?
  • How to test for an expected exception?
  • What about System.out.println(...); in tests?
  • How to data-drive tests?
  • How to time-out tests?
  • How to test the contents of a private field? (This is a trap, the answer is not to test it but to change the design.)
  • Does full code coverage mean the code is fully tested?
Test Driven Development
  • What are the benefits of using TDD?
  • Is TDD primarily a testing technique?
  • When do you write tests? (This is a joke and the expected answer is "all the f*cking time" according to Bryan Liles' TATFT.)
  • What should you do when you cannot add another test?
  • If the code passes all the unit tests why should you still change (refactor) it?
  • Why not refactor on a red bar?
Mocking and Test Doubles
  • Why use stubs or mocks?
  • How are objects called that are passed around but never actually used?
  • How are objects called that can return fixed values in answer to calls made.
  • How are objects called that can verify the behaviour of the system under test, in addition to using asserts to verify its state.
  • What is used for testing state?
  • What is used for testing behaviour?
  • What is a spy?
ExamRefactoring
  • What is your favourite Refactoring?
  • How do we refactor? (This is a word play and the expected answer is mercilessly.)
  • Should Refactoring and adding new code be done at the same time?
  • During Refactoring, how long does your code not compile?
  • During Refactoring, when should we run the tests?
  • What Refactoring can be used when a method is too long, has duplicated code or Feature Envy?
  • What Refactoring can be applied to long parameter lists?
  • In Eclipse, what do the short-cuts Alt-Shift-R, Alt-Shift-L and Alt-Shift-M do?
Working with Legacy Code
  • What is Legacy Code?
  • How can you break dependencies?
  • What are Singletons and why are they evil?
  • Do you write them?
Using these questions, small exercises and short movies I kept the participants fully engaged for a whole day of TDD theory. It was awesome!

28 May 2012

Eclipse Plugin Unit Testing

I will describe the set-up of a unit testing infrastructure for a big RCP application consisting of several plugins. In the first part I will write about how to run JUnit tests inside Eclipse.

PlugsTest Plugins
First we need a place to put the tests. We do not want to put the tests in the same project as the production code because we do not want to ship the tests. So for every plugin which we want to write tests for, we create a separate plugin with the same name suffixed with ".test". For example let's assume we want to write a JUnit test for a class in the company.product.general plugin. First we look for a plugin named company.product.general.test. Does it exist? Maybe we never used it and need to check it out from version control. Still nothing? OK, so we need to create it.

For a new test plugin we create a fragment project. We do that by selecting File > New > Project > Plug-in Development > Fragment Project. A fragment allows us to add code to another plug-in, known as the host. The fragment is merged with its host and has full access to all the packages declared in its host, not only the exported ones. Among other ways to set up tests for plugins, fragments generally are the best solution. So our unit tests have access to all classes of the host plugin. The fragment inherits all dependencies from the host. The only explicit required dependency of the test plugin is org.junit4. (Remember that various files in the build system might need to be updated for new (test) plugins to be part of the build. These might include some kind of loading rules, certain Ant build files or test features.)

The above set-up is enough to run simple JUnit tests which do not use any feature of Eclipse's OSGI container. To enable PDE JUnit tests the host plugin needs to define Eclipse-ExtensibleAPI: true in its MANIFEST.MF file. This allows the fragment to access classes from the host plugin and tells the PDE tooling to add the fragment to the classpath of the host plugin.

FragmentsTest Packages
We use the plugin's name as base package of the plugin's source code to avoid name collisions. For example all packages of the plugin company.product.general are sub packages of company.product.general. This is not the case for fragments, as fragments are merged with the host. All packages of the company.product.general.test fragment are still sub packages of company.product.general.

The package with the same name as the test fragment is used for common test set-up or custom assertion logic that might be used for more than one test. For example the package company.product.general.test might contain a class called UsLocale, which sets the current locale to US, as needed to test some business logic. Common test code can be reused by other test plugins if it is exported from the fragment. This works the same way as for normal plugins.

Warning about "Add Required Plugins"
Sometimes it is necessary to add new plugins to a launch configuration in order for the application to start. When you do that by using the "Add Required Plugins" button in the launch configuration, make sure that all the test plugins are not selected afterwards. We had some issues when test-only functionality somehow "leaked" into production.

Simple JUnit Tests
When the test plugin is ready, we can start writing simple JUnit tests. They will not necessarily be "simple", they are just called like that to distinguish them from PDE JUnit tests which have a more complex set-up. Even when developing RCP applications, these simple JUnit tests have their use. We can use them to test any class that is not dependent on the Eclipse Platform API. They are particularly useful for testing business logic and model classes.

JUnit tests go into the same Java package as the class under test. So the test plugin has the same packages as the host plugin. Test classes are named like the class under test suffixed with "Test". For example let's assume we want to test the class company.product.general.api.CatchHandlers in the plugin company.product.general. The related test is company.product.general.api.CatchHandlersTest in the company.product.general.test plugin.

FakeMocking
Unit testing is supposed to test classes or methods in isolation but classes usually depend on other classes. For more complex scenarios we want to use different objects than the live ones to get rid of these dependencies. These objects are provided to the class under test. By using them we can verify logic independently of the depended-on objects. Such objects are called Test Doubles.

Dummy objects, fakes and stubs are created easily with custom classes. But true mocks need some more logic to verify the order of method invocations (which needs some kind of state machine). Fortunately there are several frameworks that bring mocks to Java, for example EasyMock. To use it in our RCP application we need to create on OSGI bundle (i.e. an Eclipse plugin) from its jars. Let the plugin company.product.test.mock contain the mocking framework's jars. To use its classes in tests add it to the dependencies of the test fragment.

PDE JUnit Tests
PDE or Plugin JUnit tests are executed by a special test runner that launches another Eclipse instance and executes the test methods within that workbench. So PDE JUnit tests can be used for classes that are dependent on Eclipse Platform API. Parts of the Eclipse platform are available outside a running workbench as well, so a normal JUnit test might still be an option. Additionally some other parts, for example the extension registry can be mocked. But there are cases where a running workbench is necessary. For example you may assume a particular behaviour of Plugin.getStateLocation(), which would not be available if you were just using an ordinary JUnit test. Besides that the tests themselves look exactly like any other test.

When automating the build these PDE tests should be distinguished from basic ones. So we follow a different naming convention and call them *PlatformTests. Also note that the usual class extension mechanism might not work inside the workbench. You need to introduce interfaces for the types you want to mock.

20 May 2012

Mocking the Eclipse Extension Registry

Some classes of a RCP application might make use of Extension Points, calling Platform.getExtensionRegistry() and evaluating the returned configuration elements. It is possible to mock (in fact stub) the default registry provider by calling RegistryFactory.setDefaultRegistryProvider() with a registry implementation. By using a fake registry some PDE JUnit test cases can be converted to plain JUnit tests, which speeds up their execution.

A Changing Registry Factory
The default registry provider can only be set once. So we need to register a wrapper, which delegates to a RegistryFactory so it can be changed among tests.
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IExtensionRegistry;
import org.eclipse.core.runtime.RegistryFactory;
import org.eclipse.core.runtime.spi.IRegistryProvider;

public class ChangingRegistryFactory {

  private static IRegistryProvider registryProvider;
  private static boolean defaultRegistryHasBeenSet;

  public static void setDefaultRegistryProvider(IRegistryProvider provider)
                                                       throws CoreException {
    setRegistryProvider(provider);
    synchronized (ChangingRegistryFactory.class) {
      setDefaultRegistryProviderOnce();
    }
  }

  private static void setRegistryProvider(IRegistryProvider provider) {
    registryProvider = provider;
  }

  private static void setDefaultRegistryProviderOnce() throws CoreException {
    if (!defaultRegistryHasBeenSet) {
      setDefaultRegistryProvider();
      defaultRegistryHasBeenSet = true;
    }
  }

  private static void setDefaultRegistryProvider() throws CoreException {
    RegistryFactory.setDefaultRegistryProvider(new IRegistryProvider() {
      public IExtensionRegistry getRegistry() {
        return registryProvider.getRegistry();
      }
    });
  }

}
PlatformAn Extension Point Mockery
Using EasyMock or any other mock framework we can create a mock registry and register it to the RegistryFactory (in fact to the ChangingRegistryFactory). To hide the mocking details we provide a specific builder like API in the helper class ExtensionPointMockery which helps mocking Extension Points:
import static org.easymock.EasyMock.*;

public class ExtensionPointMockery {

  private final IExtensionRegistry registry = createRegistry();

  @SuppressWarnings("unused")
  public ExtensionPointMockery() throws CoreException {
    // allow CoreException to be thrown from initialiser blocks
  }

  private IExtensionRegistry createRegistry() {
    return createMock(IExtensionRegistry.class);
  }

  public IConfigurationElement confWith(Object specificInstance)
                                                       throws CoreException {
    IConfigurationElement confElement = createMock(IConfigurationElement.class);
    expect(confElement.createExecutableExtension("class")).
          andReturn(specificInstance).anyTimes();
    replay(confElement);
    return confElement;
  }

  public IConfigurationElement mockFor(Class<?> type) throws CoreException {
    Object mockInstance = createNiceMock(type);
    replay(mockInstance);
    return confWith(mockInstance);
  }

  public void set(String key, IConfigurationElement... elements) {
    expect(registry.getConfigurationElementsFor(key)).
          andReturn(elements).anyTimes();
  }

  public void setAll(IConfigurationElement... elements) {
    expect(registry.getConfigurationElementsFor(anyObject(String.class))).
          andReturn(elements).anyTimes();
  }

  public void close() throws CoreException {
    replay(registry);

    IRegistryProvider provider = createMock(IRegistryProvider.class);
    expect(provider.getRegistry()).andReturn(registry).anyTimes();
    replay(provider);

    ChangingRegistryFactory.setDefaultRegistryProvider(provider);
  }

}
Usage
Its typical usage looks like
new ExtensionPointMockery() {{
  set("preferenceSettings", mockFor(IPreferenceSettings.class));
  set("filterManager", confWith(new FilterManagerDelegate()));
  set("postProcessor");
}}.close();
where confWith() puts the given object directly into the registry, simulating its contribution and mockFor() creates a "nice mock" (a fake) of the given interface and adds it to the configuration. The call of set() without any parameter initialises the extension registry for the given name but without any contributions. Finally close() creates the mock registry and registers it to the platform.

Happy mocking!