Skip to content

Instantly share code, notes, and snippets.

@ashif-ismail
Forked from jmaicher/Unit.java
Created June 6, 2017 06:17
Show Gist options
  • Save ashif-ismail/af5492367ba9307b13091d9a97be37f5 to your computer and use it in GitHub Desktop.
Save ashif-ismail/af5492367ba9307b13091d9a97be37f5 to your computer and use it in GitHub Desktop.
Unit testing anonymous inner classes as event listener
public class Unit {
public Unit(EventDispatcher dispatcher) {
dispatcher.addHandler(MyEvent.class, new IEventHandler() {
public void onEvent(MyEvent event) {
// some behavior
}
});
}
}
public class UnitTest {
@Test
public void whenDispatcherTriggersMyEventThenIExpectBehaviour() {
EventDispatcher mockedDispatcher = mock(EventDispatcher.class);
new Unit(mockedDispatcher);
ArgumentCaptor<IEventHandler> myEventHandlerCaptor = ArgumentCaptor.forClass(IEventHandler.class);
verify(mockedDispatcher).addHandler(eq(MyEvent.class), myEventHandlerCaptor.capture());
IEventHandler myEventHandler = myEventHandlerCaptor.getValue();
MyEvent mockedEvent = mock(MyEvent.class);
myEventHandler.onEvent(mockedEvent);
// verify behavior
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment