Skip to content

Instantly share code, notes, and snippets.

@jmaicher
Created December 11, 2012 10:06
Show Gist options
  • Save jmaicher/4257510 to your computer and use it in GitHub Desktop.
Save jmaicher/4257510 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
}
}
@claussni
Copy link

  1. Java syntax?
  2. What is the responsibility of ConnectionManager? Whenever a ConnectionEvent gets issued by this Server instance, the ConnectionManager instance tracks the events connection? To me it is unclear, why the ConnectionManager is configuring the Server at all. Maybe it should be called ServerConfigurator. About Managers: http://c2.com/cgi/wiki?DontNameClassesObjectManagerHandlerOrData
  3. Java package names go like: org.jmaicher.connection;. You don't want to have a src/main/java/connection_manager directory, do you?
  4. Interface names in Java are usually not prefixed with the letter "I". This is .net-Style.

@jmaicher
Copy link
Author

Let's put 1, 3 and 4 aside, they doesn't matter at all right now.
I made up this example and quickly wrote it in the textarea to show some concrete testworthy behavior. Let's exchange ConnectionManager with ServerMonitor and say it needs to display current connections to the user. The pattern doesn't change.

@claussni
Copy link

Its all about naming things ;-) #ServerObserver

@ashif-ismail
Copy link

@jmaicher
thanks man,this one helped me ..

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment