I made a change in the blogger configuration to ease the later work when blogging. It is possible that older entries are not correctly formatted.

Wednesday 27 June 2012

Mocking

Since I keep being annoyed at my inability to test classes quickly, I have to see if I can improve the speed of the testing using mocks. Mocks can be used in different ways. In particular they can be used in behavioral testing.

The idea us that instead of injecting existing classes in a code, one puts mocks which expect actions from the caller.

To illustrate the point, it is good to use an interface for the class called (and therefore to be mocked) and a class calling this interface. We first define the interface: Algorithm.

public interface Algorithm {
   void perform();
}

Then we define the AlgorithmUser class which calls the algorithm. We give it an algorithm.

public class AlgorithmUser {
  void performAlgorithm(Algorithm algorithm){
    algortihm.perform();
  }
}

After that we define a test and create a mock instance and define the expectations. To do this we use the JMock library.


@RunWith(JMock.class)
public class PublisherTest {

  private Mockery context = new JUnit4Mockery();

  @Test
  public void testPerformAlgorithm(Algorithm algorithm){
    // create the mock
    final Algorithm algorithm = context.mock(Algorithm.class);
    // create the expectations
    context.checking(new Expectations() {
      {
        oneOf(algorithm).perform();
      }
    });
    // perform
    new AlgorthmUser().performAlgorthm(algorithm);

  }
}

The power of mocks reside in the language which can be used for this checking.
To user jMock, there is a cheat sheet.


The different frameworks I know of: