Getting StartedThis guide assumes you are familiar with unit-testing and JUnit . For a simple example we are going to test a publish/subscribe message system. A Publisher sends objects to zero or more Subscribers. We want to test the Publisher, which involves testing its interactions with its Subscribers. The Subscriber interface looks like this: interface Subscriber { void receive(Object message); } We will test that a Publisher sends a message to a single registered Subscriber. To test interactions between the Publisher and the Subscriber we will use a mock Subscriber object. First we set up the context in which our test will execute. We create a Publisher to test. We create a mock Subscriber that should receive the message. We then register the Subscriber with the Publisher. Finally we create a message object to publish. Mock mockSubscriber = new Mock(Subscriber.class); Publisher publisher = new Publisher(); publisher.add((Subscriber) mockSubscriber.proxy()); final Object message = new Object(); Next we define expectations on the mock Subscriber that specify the methods that we expect to be called upon it during the test run. We expect the receive method to be called with a single argument, the message that will be sent. We don't need to specify what will be returned from the receive method because it has a void return type. mockSubscriber.expect("receive", message); We then execute the code that we want to test. publisher.publish(message); Finally we verify that the mock Subscriber was called as expected. If we do not verify our test will detect incorrect calls to the mock Subscriber but not the complete lack of calls. mockSubscriber.verify(); Here is the complete test. public void testOneSubscriberReceivesAMessage() { // set up Mock mockSubscriber = new Mock(Subscriber.class); Publisher publisher = new Publisher(); publisher.add((Subscriber) mockSubscriber.proxy()); final Object message = new Object(); // expectations mockSubscriber.expect("receive", message); // execute publisher.publish(message); // verify mockSubscriber.verify(); } |