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