NotificationDataFetcher implements DataFetcher<SortedSet<Notification>> { @Nullable @Override public SortedSet<Notification> get(DataFetchingEnvironment environment) { final String username = environment.getArgument("username"); if (Strings.isNullOrEmpty(username)) { return null; } final Optional<UserNotifications> notifications; try { notifications = store.fetch(username); } catch (NotificationStoreException e) { LOGGER.error("Unable to fetch notifications", e); return null; } if (!notifications.isPresent()) { return Collections.emptySortedSet(); } return notifications.get().getNotifications(); } NotificationDataFetcher(final NotificationStore store); @Nullable @Override SortedSet<Notification> get(DataFetchingEnvironment environment);  }
@Test public void testUsernameNull() throws Exception { when(environment.getArgument("username")).thenReturn(null); final SortedSet<Notification> actual = fetcher.get(environment); assertThat(actual).isNull(); verify(store, never()).fetch(anyString()); }
@Test public void testUsernameEmpty() throws Exception { when(environment.getArgument("username")).thenReturn(""); final SortedSet<Notification> actual = fetcher.get(environment); assertThat(actual).isNull(); verify(store, never()).fetch(anyString()); }
@Test public void testStoreException() throws Exception { when(environment.getArgument("username")).thenReturn("test"); doThrow(new NotificationStoreException()).when(store).fetch(anyString()); final SortedSet<Notification> actual = fetcher.get(environment); assertThat(actual).isNull(); verify(store).fetch(eq("test")); }
@Test public void testNoNotifications() throws Exception { when(environment.getArgument("username")).thenReturn("test"); when(store.fetch(anyString())).thenReturn(Optional.empty()); final SortedSet<Notification> actual = fetcher.get(environment); verify(store).fetch(eq("test")); assertThat(actual).isNotNull(); assertThat(actual).isEmpty(); }
@Test public void testFetchNotifications() throws Exception { when(environment.getArgument("username")).thenReturn("test"); final Notification n1 = Notification.create("1"); final Notification n2 = Notification.create("2"); final Notification n3 = Notification.create("3"); final Notification n4 = Notification.create("4"); final TreeSet<Notification> set = new TreeSet<>(); set.add(n1); set.add(n2); set.add(n3); set.add(n4); final UserNotifications notifications = new UserNotifications(set); when(store.fetch(anyString())).thenReturn(Optional.of(notifications)); final SortedSet<Notification> actual = fetcher.get(environment); verify(store).fetch(eq("test")); assertThat(actual).isNotNull(); assertThat(actual.first()).isEqualTo(n4); assertThat(actual.last()).isEqualTo(n1); assertThat(actual.size()).isEqualTo(4); }