Main structure of a test with lmock

dfurodet edited this page Nov 22, 2011 · 1 revision

Main structure of a test with Lmock

A test that implies mock always consists in:

Defining mock objects

Given an interface that you want to stub or mock in a test, you must create a mock of that interface using Mock.getObject:

import com.vmware.lmock.Mock;
public class MyTest {
  // A Mock object implementing the contract of interface Foo:
  final Foo myMock = Mock.getObject(Foo.class);

You may also give an explicit name to your mocks, in order to simplify the understanding of error in case of failure. For example:

  final Foo myMock = Mock.getObject("foo", Foo.class);

Writing the test

Lmock offers different techniques to write tests, but the simplest one is called masquerades. It offers a very simple syntax to declare stubs and expectations while writing the tests. With masquerades, you can mix the declarations with the test itself (though, most of the time, you will declare the stubs and expectations first and then perform the test). This implies to explicitly define the beginning and the end of the masquerade:

import static com.vmware.lmock.masquerade.Schemer.*;
public class MyTest {
  void anExampleOfTest() {
    // You should now define the stubs and expectations used by the test
    // and then the test itself

Notice that you can put the invocation to begin in a setup routine. You may also put end in a teardown method, but this is a little bit trickier (see 'The issue with teardown')...

As already mentioned, the body of a test mainly consists in two tasks:

##The issue with teardown

As explained in the Scenario section, one of the purpose of end is to check of all the expectations of the scenario are met. If this is not the case, Lmock raises an error. Since the teardown procedure of a JUnit tests (tearDown() in JUnit3, @After in JUnit4) prevails on the test itself, such an error may hide previous errors raised during the execution of the test (e.g. assertion errors).

This typical behavior (we have the similar issue with assertIsSatisfied in JMock) can't really be bypassed, except by invoking end in the body of the test rather than a teardown procedure.