Johan,
thanks for all the suggestion and info. To give a little background
this class had zero test coverage and the Subscription class was a
subscriber to JMS messaging queue so for it to function, I'd need the
running message broker and this message handler would need to be
deployed on my J2EE container so I thought I'd mock it. Basicly it
provides a payload from the queue (large XML string) to a xml parser
and then the code converts it into the POJO to be persisted. So the
build method needs to return a large xml charachter string. I got this
to work and this is what I did:
@RunWith(PowerMockRunner.class)
@PrepareForTest({EventHandler.class,Subscription.class})
public class EventHandler_UT {
@Mock
EssDataDAO mockEssDataDAO;
@Mock
Builder mockBuilder;
@InjectMocks
EventHandler myEventHandler=new EventHandler();
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
}
@Test
public void testHandleEventHappyPath() throws Exception{
whenNew(Subscription.Builder.class).withArguments(anyString()).thenReturn(mockBuilder);
Subscription mockSubscription = createMock(Subscription.class);
when(mockBuilder.build()).thenReturn(mockSubscription);
expect(mockSubscription.getMessage()).andReturn(getPayload());
replay(mockSubscription);
myEventHandler.handleEvent("any string");
verify(mockEssDataDAO,times(2)).save((EssData)anyObject());
}
}
This is just a very abbreviated version of everything but I show
new'ing the inner static class, which was nothing tricky but mocking
the final class which had the method getMessage is where the xml
payload would be. I did not know I didn't need
MockitoAnnotations.initMocks(this). At first I was confused because
the EventHandler had no setter for the DAO nor a constructor passing
it in. But marking mockDAO with @Mock works. Also, I did not know
about the supress method. All good tips thank you. Interestingly
Builder is a static class but build requires nothing special for it's
call to return something. The call on getMessage does require some
extra work though being that I was mocking the final class
Subscription.
Mike