Skip to content
This repository has been archived by the owner on Nov 9, 2020. It is now read-only.

Behaviors

dfurodet edited this page Nov 22, 2011 · 1 revision

#Behaviors

Behaviors allow to define what Lmock does when the test invokes a specific method of a mock:

  • Return a value (if the method is expected to do so)
  • Throw an exception
  • Invoke a specific handler

##Returning a value

This is specified with the directive willReturn, as illustrated below:


import static com.vmware.lmock.masquerade.Schemer.*;
...
public class MyTest {
  final List mockList = Mock.getObject("mock list", List.class);
  ...
  void aTestIllustratingWillReturn() {
    begin();
    // Define two stubs: one simulates the fact that the list is not empty, the second one that
    // the first string in the list is "Hello World":
    willReturn(false).when(myList).isEmpty();

    ...

##Throwing an exception

This is specified with the directive willThrow, as illustrated below:


import static com.vmware.lmock.masquerade.Schemer.*;
...
public class MyTest {
  final List mockList = Mock.getObject("mock list", List.class);
  ...
  void aTestIllustratingWillThrow() {
    begin();
    // Define two stubs: one simulates the fact that the list is not empty, the second one that
    // the first string in the list is "Hello World":
    willThrow(new IndexOutOfBoundsException()).when(myList).get(1);

    ...

##Delegating to a specific handler

This procedure allows to plug your own behavior upon an invocation (this is called delegation). To do so, you must:

  • Define an InvocationResultProvider, which implements the apply routine, performing your own set of operations
  • Use willDelegateTo to plug this provider to the mock invocation

Next is an example of delegation:


import static com.vmware.lmock.masquerade.Schemer.*;
import com.vmware.lmock.impl.InvocationResultProvider;
...
public class MyTest {
  final List mockList = Mock.getObject("mock list", List.class);
  ...
  private final InvocationResultProvider myHandler = new InvocationResultProvider() {
    public Object apply() {
      // DO YOUR OWN PROCESSING HERE... For example:
      System.out.println("gotcha!");
      // The method must return an object that matches the return value of the invoked method...
      // For example:
      return "12345";
    }
  };
  ...
  public void aTestIllustratingWillDelegate() {
    begin();
    willDelegateTo(myHandler).when(myList).get(0);
    ...
  }
  ...
}

This procedure is pretty dangerous and should used with caution. More specifically, apply MUST NOT invoke another mock.