1 /* 2 * Copyright (C) 2007 The Guava Authors 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.google.common.eventbus; 18 19 import com.google.common.collect.Lists; 20 import java.util.List; 21 import junit.framework.TestCase; 22 23 /** 24 * Validate that {@link EventBus} behaves carefully when listeners publish their own events. 25 * 26 * @author Jesse Wilson 27 */ 28 public class ReentrantEventsTest extends TestCase { 29 30 static final String FIRST = "one"; 31 static final Double SECOND = 2.0d; 32 33 final EventBus bus = new EventBus(); 34 testNoReentrantEvents()35 public void testNoReentrantEvents() { 36 ReentrantEventsHater hater = new ReentrantEventsHater(); 37 bus.register(hater); 38 39 bus.post(FIRST); 40 41 assertEquals( 42 "ReentrantEventHater expected 2 events", 43 Lists.<Object>newArrayList(FIRST, SECOND), 44 hater.eventsReceived); 45 } 46 47 public class ReentrantEventsHater { 48 boolean ready = true; 49 List<Object> eventsReceived = Lists.newArrayList(); 50 51 @Subscribe listenForStrings(String event)52 public void listenForStrings(String event) { 53 eventsReceived.add(event); 54 ready = false; 55 try { 56 bus.post(SECOND); 57 } finally { 58 ready = true; 59 } 60 } 61 62 @Subscribe listenForDoubles(Double event)63 public void listenForDoubles(Double event) { 64 assertTrue("I received an event when I wasn't ready!", ready); 65 eventsReceived.add(event); 66 } 67 } 68 testEventOrderingIsPredictable()69 public void testEventOrderingIsPredictable() { 70 EventProcessor processor = new EventProcessor(); 71 bus.register(processor); 72 73 EventRecorder recorder = new EventRecorder(); 74 bus.register(recorder); 75 76 bus.post(FIRST); 77 78 assertEquals( 79 "EventRecorder expected events in order", 80 Lists.<Object>newArrayList(FIRST, SECOND), 81 recorder.eventsReceived); 82 } 83 84 public class EventProcessor { 85 @Subscribe listenForStrings(String event)86 public void listenForStrings(String event) { 87 bus.post(SECOND); 88 } 89 } 90 91 public class EventRecorder { 92 List<Object> eventsReceived = Lists.newArrayList(); 93 94 @Subscribe listenForEverything(Object event)95 public void listenForEverything(Object event) { 96 eventsReceived.add(event); 97 } 98 } 99 } 100