Failing Coder
Failing Coder

Reputation: 666

EasyMock - expect a method call that throws a checked exception

I have the follow method that rethrows the JMSException wrapped in a RuntimeException so my code doesn't have to deal with the checked exception.

public String getText(TextMessage textMessage) {
    try {
        return textMessage.getText();
    } catch (JMSException e) {
        throw new RuntimeException(e);
    }
}

I'm trying to use EasyMock, asking that the getText method throws a JMSException when called, so that I can then test that a RuntimeException is thrown.

@Test
public void getText() {
    TextMessage mockMessage = createMock(TextMessage.class);
    expect(mockTextMessage.getText()).andThrow(new JMSException("Something terrible happened"));
    replayAll();
    jmsHelper.getText(mockTextMessage);
    verifyAll();
}

I'm getting a Unhandled exception type JMSException compilation error against the expect(mockTextMessage.getText()) code.

What's the best way to write this EasyMock test?

Upvotes: 0

Views: 3221

Answers (1)

dkatzel
dkatzel

Reputation: 31648

You're doing just fine. All you have to do is make the compiler happy by making your test method throw the JMSException

@Test
public void getText() throws JMSException{
   ... 
}

The error is just because the compiler doesn't know mockTextMessage.getText() is a fake method so you have to catch or throw any exceptions it throws. Don't worry, this will never actually throw an exception.

Upvotes: 1

Related Questions