Developer Forums | About Us | Site Map
Search  
HOME > TUTORIALS > SERVER SIDE CODING > JAVA TUTORIALS > UNIT TESTING WITH MOCK OBJECTS


Sponsors





Useful Lists

Web Host
site hosted by netplex

Online Manuals

Unit testing with mock objects
By Alexander Day Chaffee & William Pietri - 2004-02-18 Page:  1 2 3 4 5 6

Refactoring: Extract and override factory method

A refactoring is a code change that leaves the original functionality intact, but changes the design of the code so that it's cleaner, more efficient, and easier to test. This section offers a step-by-step description of the Extract and Override factory method refactoring.

Problem: The object being tested creates a collaborator object. This collaborator must be replaced with a mock object.

Code before refactoring


class Application {
...
  public void run() {
    View v = new View();
    v.display();
...

Solution: Extract the creation code into a factory method, override this factory method in a test subclass, and then make the overridden method return a mock object instead. Finally, if practical, add a unit test that requires the original object's factory method to return an object of the correct type:

Code after refactoring



class Application {
...
  public void run() {
    View v = createView();
    v.display();
...
  protected View createView() {
    return new View();
  }
...
}

This refactoring enables the unit test code shown in Listing 1:

Listing 1. Unit test code


class ApplicationTest extends TestCase {

  MockView mockView = new MockView();

  public void testApplication {
    Application a = new Application() {
      protected View createView() {
        return mockView;
      }
    };
    a.run();
    mockView.validate();
  }

  private class MockView extends View
  {
    boolean isDisplayed = false;

    public void display() {
      isDisplayed = true;
    }

    public void validate() {
      assertTrue(isDisplayed);
    }
  }
}

Roles

This design introduces the following roles played by objects in the system:

  • Target object: The object being tested
  • Collaborator object: The object created or obtained by the target
  • Mock object: A subclass (or implementation) of the collaborator that follows the mock object pattern
  • Specialization object: A subclass of the target that overrides the creation method to return a mock instead of a collaborator


View Unit testing with mock objects Discussion

Page:  1 2 3 4 5 6 Next Page: Mechanics

First published by IBM developerWorks


Copyright 2004-2017 GrindingGears.com. All rights reserved.
Article copyright and all rights retained by the author.