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);
    }
    
}