Thursday, August 20, 2015

jMock in 5 minutes

JMock makes it easy to mock up objects in unit tests.

Create Mock Objects



Use annotations @Rule and @Mock to create mock objects.


import org.jmock.auto.Mock;
import org.jmock.integration.junit4.JUnitRuleMockery;
import org.junit.Rule;
import org.junit.Test;


public class GettingStartedTest {
    //The rule context field must be public
    @Rule public final JUnitRuleMockery context = new JUnitRuleMockery();
    @Mock private Runnable runnable;
   
   @Test
   public void testInvocation() {  
        ...  
   }
    
}


Alternatively, you can define the mock object as follows:


Mockery context = new JUnit4Mockery();
private Runnable runnable = context.mock(Runnable.class);


Set Expectations on Invocations



    @Test
    public void testInvocation() {    
       
    // Set invocation expectations.
    // You can use:
    //     oneOf, exactly(n).of,
    //     atLeast(n).of, atMost(n).of, between(min, max).of
    //     allowing, never
    // For details, see http://www.jmock.org/cardinality.html
    context.checking(new Expectations() {{
      //The method runnable.run() will be invoked once and once only.
      oneOf (runnable).run();
        }});
             
    runnable.run();
     }


Mock (or Set Expectations on) Return Results



import static org.junit.Assert.*;
import java.util.Map;
import org.jmock.Expectations;
import org.jmock.auto.Mock;
import org.jmock.integration.junit4.JUnitRuleMockery;
import org.junit.Rule;
import org.junit.Test;


public class MockResultTest {
@Rule public final JUnitRuleMockery context = new JUnitRuleMockery();
@Mock private Map map;
   
    @Test
    public void testMockedResults() {    
       
    context.checking(new Expectations() {{
       
      oneOf(map).get("Jason");
      will(returnValue(10));
     
      oneOf(map).get("Jay");
      will(returnValue(5));
     
      // You cannot define as follows:
      //    allowing(map).get("Jason"); ...
      //    allowing(map).get("Jay"); ...
      // The 2nd allowing does not take effect.
     
      allowing(map).remove(with(any(String.class)));
      will(returnValue(100));
        }});
             
    assertEquals(map.get("Jason"), 10);
    assertEquals(map.get("Jay"), 5);
    assertEquals(map.remove("foo"), 100);
  }
}


References