Author Login
Post Reply
Good day,
I'm trying to test that my Class Under Test actually throws an exception when I believe it will. I've created some sample code and pasted it all below. Please see the *** areas in the below code, and I've also included my supporting classes code if you need it at the bottom of this post.
Here's the problem I'm having. JMock only allows you to put Mocked objects in your "Expectations" section. I want to verify that when a Mocked object returns a value which will cause my Class Under Test to throw an exception, that it actually does throw an exception. I've verified that my code works by adding a "System.out.println("Got to here");" statement in the "catch" block below, but that's not repeatable, automated Unit testing. Please help me understand how I can do this in a repeatable, automated fashion.
Regards,
Joseph Ford
//PublisherTest.java
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.junit.Test;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class PublisherTest {
Mockery context = new Mockery();
@Test
public void testGetMessagesFromOneSubscriberReturnsException() {
//setup
final Subscriber subscriber = context.mock(Subscriber.class);
final Publisher publisher = new Publisher();
publisher.add(subscriber);
//expectations
context.checking(new Expectations() {{
exactly(1).of(subscriber).getSubscriberID(); will(returnValue(2));
//***NOT ALLOWED***exactly(1).of(publisher).getMessagesFromOneSubscriber(1); will(throwException(new NoSuchElementException ()));
}});
//execute
try {
@SuppressWarnings("unused")
Iterator<String> anIterator = publisher.getMessagesFromOneSubscriber(1);
} catch (NoSuchElementException exception) {
//***How do I test that I got to here?***
}
//verify
context.assertIsSatisfied();
}
}
//Publisher.java
import java.util.ArrayList;
import java.util.ListIterator;
import java.util.NoSuchElementException;
public class Publisher {
ArrayList<Subscriber> list;
public Publisher() {
list = new ArrayList<Subscriber>();
}
public void add(Subscriber subscriber) {
list.add(subscriber);
}
public void publish(String message) {
for (int j = 0; j < list.size(); j++)
list.get(j).receive(message);
}
public ListIterator<String> getMessagesFromOneSubscriber(int subscriberID) throws NoSuchElementException {
ListIterator<Subscriber> anIterator = list.listIterator(0);
while (anIterator.hasNext()) {
if (anIterator.next().getSubscriberID() == subscriberID)
return anIterator.previous().getHistoricalMessages();
}
throw new NoSuchElementException();
}
}
//Subscriber.java
import java.util.ListIterator;
public interface Subscriber {
public void receive(String message);
public int getSubscriberID();
public ListIterator<String> getHistoricalMessages();
}