• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
21 import junit.framework.TestCase;
22 
23 import java.util.List;
24 import java.util.concurrent.Executor;
25 
26 /**
27  * Test case for {@link AsyncEventBus}.
28  *
29  * @author Cliff Biffle
30  */
31 public class AsyncEventBusTest extends TestCase {
32   private static final String EVENT = "Hello";
33 
34   /** The executor we use to fake asynchronicity. */
35   private FakeExecutor executor;
36   private AsyncEventBus bus;
37 
setUp()38   @Override protected void setUp() throws Exception {
39     super.setUp();
40     executor = new FakeExecutor();
41     bus = new AsyncEventBus(executor);
42   }
43 
testBasicDistribution()44   public void testBasicDistribution() {
45     StringCatcher catcher = new StringCatcher();
46     bus.register(catcher);
47 
48     // We post the event, but our Executor will not deliver it until instructed.
49     bus.post(EVENT);
50 
51     List<String> events = catcher.getEvents();
52     assertTrue("No events should be delivered synchronously.",
53         events.isEmpty());
54 
55     // Now we find the task in our Executor and explicitly activate it.
56     List<Runnable> tasks = executor.getTasks();
57     assertEquals("One event dispatch task should be queued.", 1, tasks.size());
58 
59     tasks.get(0).run();
60 
61     assertEquals("One event should be delivered.", 1, events.size());
62     assertEquals("Correct string should be delivered.", EVENT, events.get(0));
63   }
64 
65   /**
66    * An {@link Executor} wanna-be that simply records the tasks it's given.
67    * Arguably the Worst Executor Ever.
68    *
69    * @author cbiffle
70    *
71    */
72   public static class FakeExecutor implements Executor {
73     List<Runnable> tasks = Lists.newArrayList();
74 
75     @Override
execute(Runnable task)76     public void execute(Runnable task) {
77       tasks.add(task);
78     }
79 
getTasks()80     public List<Runnable> getTasks() {
81       return tasks;
82     }
83   }
84 
85 }
86