3232package org .scijava .event ;
3333
3434import static org .junit .Assert .assertEquals ;
35+ import static org .junit .Assert .assertNotNull ;
3536import static org .junit .Assert .assertNull ;
37+ import static org .junit .Assert .assertTrue ;
3638
3739import java .lang .ref .WeakReference ;
3840
3941import org .junit .Test ;
4042import org .scijava .Context ;
43+ import org .scijava .plugin .Plugin ;
44+ import org .scijava .service .AbstractService ;
45+ import org .scijava .service .Service ;
46+ import org .scijava .service .event .ServicesLoadedEvent ;
4147
4248/**
4349 * Verifies that the SciJava event service works as expected.
@@ -74,6 +80,21 @@ public void testWeakEventHandlers() {
7480 assertEquals (1 , counter );
7581 }
7682
83+ /**
84+ * Tests that when a service has methods labeled with {@code @EventHandler}
85+ * annotations, the {@link EventService} will be brought in as a dependency.
86+ */
87+ @ Test
88+ public void testEventHandlerDependencies () throws InterruptedException {
89+ final Context context = new Context (ServiceNeedingAnEventService .class );
90+ final EventService eventService = context .getService (EventService .class );
91+ final ServiceNeedingAnEventService snaeService =
92+ context .getService (ServiceNeedingAnEventService .class );
93+ assertNotNull (eventService );
94+ Thread .sleep (500 ); // NB: ServicesLoadedEvent is published asynchronously.
95+ assertTrue (snaeService .isContextCreated ());
96+ }
97+
7798 private static void gc () {
7899 System .gc ();
79100 // for some reason, some systems need extra encouragement to collect their garbage
@@ -94,4 +115,21 @@ public void onEvent(final MyEvent e) {
94115 e .inc ();
95116 }
96117 }
118+
119+ public static class ServiceNeedingAnEventService extends AbstractService {
120+
121+ private boolean contextCreated ;
122+
123+ public boolean isContextCreated () {
124+ return contextCreated ;
125+ }
126+
127+ @ EventHandler
128+ public void onEvent (
129+ @ SuppressWarnings ("unused" ) final ServicesLoadedEvent evt )
130+ {
131+ contextCreated = true ;
132+ }
133+ }
134+
97135}
0 commit comments