Creating multiple instances of a mock object
I modified the Publisher/Subscriber example to reject duplicate subscriber instances. It ran and passed the test that I had created. I then added the following test to show that three different subscribers would each receive the message once, when piblished:
@Test
public void testPublish3()
{
// Set up test.
final Publisher publisher = new Publisher();
final Subscriber subscriber1 = context.mock(Subscriber.class);
final Subscriber subscriber2 = context.mock(Subscriber.class);
final Subscriber subscriber3 = context.mock(Subscriber.class);
publisher.add(subscriber1);
publisher.add(subscriber2);
publisher.add(subscriber3);
final String message = "message";
// Set up expectations.
context.checking(new Expectations() {{
exactly(1).of(subscriber1).receive(message);
exactly(1).of(subscriber2).receive(message);
exactly(1).of(subscriber3).receive(message);
}});
// Execute action.
publisher.publish(message);
// Verify results.
context.assertIsSatisfied();
}
This compiles fine but the test crashed with the following error:
java.lang.IllegalArgumentException: a mock with name subscriber already exists
at org.jmock.Mockery.mock(Mockery.java:128)
at org.jmock.Mockery.mock(Mockery.java:120)
at jmock.PublisherTest.testPublish3(PublisherTest.java:61) (i.e. where subscriber2 is declared, above).
How should I have written this test?
Thanks,
Vince.