• 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 import java.util.List;
21 import java.util.concurrent.Executor;
22 import junit.framework.TestCase;
23 
24 /**
25  * Test case for {@link AsyncEventBus}.
26  *
27  * @author Cliff Biffle
28  */
29 public class AsyncEventBusTest extends TestCase {
30   private static final String EVENT = "Hello";
31 
32   /** The executor we use to fake asynchronicity. */
33   private FakeExecutor executor;
34 
35   private AsyncEventBus bus;
36 
37   @Override
setUp()38   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.", events.isEmpty());
53 
54     // Now we find the task in our Executor and explicitly activate it.
55     List<Runnable> tasks = executor.getTasks();
56     assertEquals("One event dispatch task should be queued.", 1, tasks.size());
57 
58     tasks.get(0).run();
59 
60     assertEquals("One event should be delivered.", 1, events.size());
61     assertEquals("Correct string should be delivered.", EVENT, events.get(0));
62   }
63 
64   /**
65    * An {@link Executor} wanna-be that simply records the tasks it's given. Arguably the Worst
66    * Executor Ever.
67    *
68    * @author cbiffle
69    */
70   public static class FakeExecutor implements Executor {
71     List<Runnable> tasks = Lists.newArrayList();
72 
73     @Override
execute(Runnable task)74     public void execute(Runnable task) {
75       tasks.add(task);
76     }
77 
getTasks()78     public List<Runnable> getTasks() {
79       return tasks;
80     }
81   }
82 }
83