BAEL-639: Guide to Guava's EventBus Tests

This commit is contained in:
Stephen Braimah 2017-01-31 22:21:24 +00:00
parent 03902d2507
commit b2fcd4a953
4 changed files with 114 additions and 0 deletions

View File

@ -0,0 +1,18 @@
package org.baeldung.guava;
public class CustomEvent {
private String action;
public CustomEvent(String action) {
this.action = action;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
}

View File

@ -0,0 +1,22 @@
package org.baeldung.guava;
import com.google.common.eventbus.EventBus;
class EventBusWrapper {
private static EventBus eventBus = new EventBus();
static void register(Object object){
eventBus.register(object);
}
static void unregister(Object object){
eventBus.unregister(object);
}
static void post(Object object){
eventBus.post(object);
}
}

View File

@ -0,0 +1,33 @@
package org.baeldung.guava;
import com.google.common.eventbus.Subscribe;
public class EventListener {
private static int eventsHandled;
/**
* Handles events of type String *
*/
@Subscribe
public void stringEvent(String event){
System.out.println("do event ["+event+"]");
eventsHandled++;
}
/**
* Handles events of type CustomEvent
*/
@Subscribe
public void someEvent(CustomEvent customEvent){
System.out.println("do event ["+ customEvent.getAction()+"]");
eventsHandled++;
}
public int getEventsHandled() {
return eventsHandled;
}
public void resetEventsHandled(){
eventsHandled = 0;
}
}

View File

@ -0,0 +1,41 @@
package org.baeldung.guava;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
public class GuavaEventBusTest {
private EventListener listener;
@Before
public void setUp() throws Exception {
listener = new EventListener();
EventBusWrapper.register(listener);
}
@After
public void tearDown() throws Exception {
EventBusWrapper.unregister(listener);
}
@Test
public void givenStringEvent_whenEventHandled_thenSuccess() throws Exception {
listener.resetEventsHandled();
EventBusWrapper.post("String Event");
assertEquals(1,listener.getEventsHandled());
}
@Test
public void givenCustomEvent_whenEventHandled_thenSuccess() throws Exception {
listener.resetEventsHandled();
CustomEvent customEvent = new CustomEvent("Custom Event");
EventBusWrapper.post(customEvent);
assertEquals(1,listener.getEventsHandled());
}
}