Skip to content

Instantly share code, notes, and snippets.

@marlly
Last active August 29, 2015 14:26
Show Gist options
  • Save marlly/4750601a91181b96e32f to your computer and use it in GitHub Desktop.
Save marlly/4750601a91181b96e32f to your computer and use it in GitHub Desktop.
Example of annotation driven events using EventBus (Google Guava library)
import static org.mockito.Mockito.verify;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Spy;
import org.mockito.runners.MockitoJUnitRunner;
import com.google.common.eventbus.EventBus;
@RunWith(MockitoJUnitRunner.class)
public class TestAnnotationDrivenEvent {
private final EventBus eventBus = new EventBus();
@Spy
private final MessageRecievedEventConsumer listener = new MessageRecievedEventConsumer();
@Before
public void registerListener() {
eventBus.register(listener);
}
@Test
public void fireEvent() {
Message msg = new Message("marlly", "Interface vs annotation driven events", "Post about differences between those event architectures");
MessageRecievedEvent msgEvent = new MessageRecievedEvent(msg);
eventBus.post(msgEvent);
verify(listener).messageRecieved(msgEvent);
}
}
public class Message {
private final String sender;
private final String subject;
private final String text;
public Message(String sender, String subject, String text) {
this.sender = sender;
this.subject = subject;
this.text = text;
}
public String getSender() {
return sender;
}
public String getSubject() {
return subject;
}
public String getText() {
return text;
}
}
public class MessageRecievedEvent {
private final Message msg;
public MessageRecievedEvent(Message msg) {
this.msg = msg;
}
public Message getMsg() {
return msg;
}
}
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.eventbus.Subscribe;
public class MessageRecievedEventConsumer {
private static final Logger LOG = LoggerFactory.getLogger(MessageRecievedEventConsumer.class);
@Subscribe
public void messageRecieved(MessageRecievedEvent e) {
LOG.info("messageRecieved(), msg: {}", e.getMsg());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment