The Open Enterprise Foundation

Tutoral


This guide assumes you are familiar with unit-testing and JUnit, and know the concept of Mock Objects.

interface Subscriber {
    void receive(String message);
}
		
class TestPublisher extends TestCase {
 
    public void testPublishMessage() { 
        .....
        publisher.publish("hi himock");
        assertEquals("hi himock",receiveMessage);
    }
}
		
public class TestPublisher extends TestCase{
    String receiveMessage =null;
	 
    public void testOldMockTestPublishMessage(){
        //expectations
        class MockSubscriber implements Subscriber{
            public void receive(String message) {
                receiveMessage = message;
            }
        }
		
        //set up
        Publisher publisher = new Publisher();
        MockSubscriber mockSubscriber = new MockSubscriber();
        publisher.add(mockSubscriber);
		
        // execute
        publisher.publish("hi mock");
		
        //verify
        assertEquals("hi mock",receiveMessage);
    }
}
		
public class TestPublisher extends TestCase{

    public void testHiMockPublishMessage() {
        //expectations		
        class SubscibeMocker{
            void receive(String aMessage){
                "hi mock".equals(aMessage);
            }
        }
		
        //set up
        Publisher publisher = new Publisher();
        HiMock hiMock = new HiMock();
        Subscriber mockSubscriber = (Subscriber)hiMock.mock(Subscriber.class,new SubscibeMocker());
        publisher.add(mockSubscriber);
		
        // execute
        publisher.publish("hi mock");
		
        // verify
        hiMock.verify();
    }
}
		
 
public class Publisher {
    List subscribers;
	
    public Publisher() {
        subscribers = new ArrayList();
    }
	
    public void add(Subscriber subscriber) {
        subscribers.add(subscriber);
    }
	
    public void publish(String message) {
        for(int i=0;i<subscribers.size();i++)
            ((Subscriber)subscribers.get(i)).receive(message);
    }
}