import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Publisher {
List<Subscriber> listener = new ArrayList<Subscriber>();
public void publish(String message) {
for (Iterator iterator = listener.iterator(); iterator.hasNext();) {
Subscriber s = (Subscriber) iterator.next();
s.receive(message);
}
}
public void add(Subscriber subscriber) {
listener.add(subscriber);
}
}
interface Subscriber {
void receive(String message);
}
import junit.framework.TestCase;
import org.jmock.Expectations;
import org.jmock.Mockery;
public class PublisherTest extends TestCase {
Mockery context = new Mockery();
public void testOneSubscriberReceivesAMessage() {
// set up
final Subscriber subscriber = context.mock(Subscriber.class);
Publisher publisher = new Publisher();
publisher.add(subscriber);
final String message = "message";
// expectations
context.checking(new Expectations() {{
oneOf (subscriber).receive(message);
}});
// execute
publisher.publish(message);
// verify
context.assertIsSatisfied();
}
}