The Open Enterprise Foundation

使用例子

本文档假设您已经熟练应用JUnit进行测试驱动的开发,并已经了解了使用MockObjects辅助测试。

HiMock用于生成mock对象,以方便您进行mock测试,它极其简单:我们使用了jmock的例子来描述一个publish/subscribe的过程。订阅者:

interface Subscriber {
    void receive(String message);
}
		

我们希望测试在publisher发布后,给每个Subscriber发送消息

class TestPublisher extends TestCase { 
    public void testPublishMessage() { 
        .....
        publisher.publish("hi himock");
        assertEquals("hi himock",receiveMessage);
    }
}
		

让我们看看一直使用的mock方式:实现Publisher接口:

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{//没有实现Subscriber接口,HiMock把这种伪实现叫做mocker
            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();
    }
}
		

哦,这看起来和我们以前用一个实现接口的类写mock测试很像,不过,现在更方便了,因为我们不必实现接口中所有的方法.

最后补上Publisher类

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

}