Samstag, 2. Januar 2010

Example - JMockContext - JUnit 4.7 Rule Support

JMock now contains in the SVN trunk (http://svn.codehaus.org/jmock/trunk/jmock2) a class org.jmock.integration.junit4.JMockContext, the class is a JUnit 4.7 rule. With this new JUnit rule for JMock no JUnit runner is needed to use JMock in JUnit tests.

Here a small example test which use the new JMockContext rule:
import java.util.Observer;

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

// JUH @RunWith is not needed 
public class ExampleJMockContextTest {
    
    @Rule public JMockContext context = new JMockContext();
    
    @Mock Observer mockObserver;
    
    @Test public void expectNoException(){
        context.checking(new Expectations(){{
            oneOf(mockObserver).update(null, null);
        }});
        
        mockObserver.update(null, null);
    }
    
    @Test(expected=RuntimeException.class)  
    public void expectExceptionInSUT() throws Exception {
        
        context.checking(new Expectations(){{
            oneOf(mockObserver).update(null, null);
        }});
        
        mockObserver.update(null, null);
        
        throw new RuntimeException("Exception in SUT");
    }
    
    @Test(expected=RuntimeException.class) 
    public void expectExceptionInMockObjectTest(){
        
        context.checking(new Expectations(){{
            oneOf(mockObserver).update(null, null);
            will(throwException(new RuntimeException("Observer unavailable")));
        }});
        
        mockObserver.update(null, null);
    }
    
}

1 Kommentar:

  1. Thanks for this, looks like the code changed a bit, it's now available here:

    http://svn.codehaus.org/jmock/trunk/jmock2/src/org/jmock/integration/junit4/JUnitRuleMockery.java

    and this also looks like it will be released in 2.6.0 of jMock

    -Ben

    AntwortenLöschen