001package edu.pdx.cs.joy.grader.poa; 002 003import com.google.common.eventbus.EventBus; 004import com.google.common.eventbus.Subscribe; 005import com.google.common.eventbus.SubscriberExceptionContext; 006import com.google.common.eventbus.SubscriberExceptionHandler; 007import org.junit.jupiter.api.Test; 008import org.mockito.ArgumentCaptor; 009 010import static org.hamcrest.MatcherAssert.assertThat; 011import static org.hamcrest.Matchers.equalTo; 012import static org.mockito.ArgumentMatchers.any; 013import static org.mockito.ArgumentMatchers.eq; 014import static org.mockito.Mockito.mock; 015import static org.mockito.Mockito.verify; 016 017public class UnhandledExceptionEventTest { 018 019 @Test 020 public void unhandledExceptionInEventThreadCallsSubscriberExceptionHandler() { 021 SubscriberExceptionHandler handler = mock(SubscriberExceptionHandler.class); 022 EventBus bus = new EventBus(handler); 023 024 final IllegalStateException exception = new IllegalStateException("Excepted Unhandled Exception"); 025 bus.register(new Object() { 026 @Subscribe 027 public void throwUnhandledException(TriggerUnhandledException event) { 028 throw exception; 029 } 030 }); 031 032 bus.post(new TriggerUnhandledException()); 033 034 verify(handler).handleException(eq(exception), any(SubscriberExceptionContext.class)); 035 } 036 037 private static class TriggerUnhandledException { 038 } 039 040 @Test 041 public void unhandledExceptionInEventThreadFiresUnhandledExceptionEvent() { 042 EventBusThatPublishesUnhandledExceptionEvents bus = new EventBusThatPublishesUnhandledExceptionEvents(); 043 044 UnhandledExceptionEventHandler handler = mock(UnhandledExceptionEventHandler.class); 045 bus.register(handler); 046 047 final IllegalStateException exception = new IllegalStateException("Expected Unhandled Exception"); 048 bus.register(new Object() { 049 @Subscribe 050 public void throwUnhandledException(TriggerUnhandledException event) { 051 throw exception; 052 } 053 }); 054 055 bus.post(new TriggerUnhandledException()); 056 057 ArgumentCaptor<UnhandledExceptionEvent> event = ArgumentCaptor.forClass(UnhandledExceptionEvent.class); 058 verify(handler).handle(event.capture()); 059 060 assertThat(event.getValue().getUnhandledException(), equalTo(exception)); 061 } 062 063 private interface UnhandledExceptionEventHandler { 064 @Subscribe 065 void handle(UnhandledExceptionEvent event); 066 } 067}