Monday, November 12, 2007

JMock Tests

Use the code below and compile and run as follows, modifying the path to the jar files as necessary:
javac -cp .;jmock-2.4.0.jar;junit-4.4.jar com/test/jmock/*.java
java -cp .;jmock-2.4.0.jar;junit-4.4.jar;hamcrest-library-1.1.jar 
org.junit.runner.JUnitCore com.test.jmock.PublisherTest
package com.test.jmock; 
interface Subscriber {
    void receive(String message);

package com.test.jmock; 
import java.util.ArrayList; 
import java.util.List;  
import junit.framework.*; 

class Publisher { 
 List<Subscriber> list = new ArrayList<Subscriber>(); 
 void add(Subscriber subscriber) {
 void publish(String message) {
  Subscriber s = list.get(0); 

package com.test.jmock;
import org.jmock.Mockery;
import org.jmock.Expectations;
import org.junit.*;

public class PublisherTest {
    Mockery context = new Mockery();

    public void testOneSubscriberReceivesAMessage() {
        // set up
        final Subscriber subscriber = context.mock(Subscriber.class);

        Publisher publisher = new Publisher();
        final String message = "message";
        // expectations
        context.checking(new Expectations() {{
            one (subscriber).receive(message);

        // execute
        // verify