ScheduledSubscriptionsService extends AbstractService implements Runnable { @Override public void run() { logger.debug("Refresh subscriptions #{} started at {}", counter.incrementAndGet(), Instant.now().toString()); final Set<String> apiIds = apiService.findAllLight().stream() .map(ApiEntity::getId) .collect(toSet()); final SubscriptionQuery query = new SubscriptionQuery(); query.setApis(apiIds); query.setStatuses(Collections.singleton(SubscriptionStatus.ACCEPTED)); final Collection<SubscriptionEntity> subscriptions = subscriptionService.search(query); final Date now = new Date(); subscriptions .forEach(subscription -> { if (subscription.getEndingAt() != null && subscription.getEndingAt().before(now)) { subscriptionService.close(subscription.getId()); } }); logger.debug("Refresh subscriptions #{} ended at {}", counter.get(), Instant.now().toString()); }  @Override void run();  }
@Test public void shouldCloseOutdatedSubscriptions() { ApiEntity apiEntity = mock(ApiEntity.class); when(apiEntity.getId()).thenReturn("API_ID"); SubscriptionEntity endDateInThePast = createSubscription( "end_date_in_the_past", SubscriptionStatus.ACCEPTED, new Date(0)); SubscriptionEntity noEndDate = createSubscription( "no_end_date", SubscriptionStatus.ACCEPTED, null); SubscriptionEntity endDateInTheFuture = createSubscription( "end_date_in_the_future", SubscriptionStatus.ACCEPTED, new Date(Long.MAX_VALUE)); when(apiService.findAllLight()).thenReturn(Collections.singleton(apiEntity)); SubscriptionQuery query = new SubscriptionQuery(); query.setApi(apiEntity.getId()); query.setStatuses(Collections.singleton(SubscriptionStatus.ACCEPTED)); when(subscriptionService.search(query)). thenReturn(new HashSet<>(Arrays.asList( endDateInThePast, noEndDate, endDateInTheFuture))); service.run(); verify(apiService, times(1)).findAllLight(); verify(subscriptionService, times(1)).search(query); verify(subscriptionService, times(1)).close("end_date_in_the_past"); verify(subscriptionService, never()).close("no_end_date"); verify(subscriptionService, never()).close("end_date_in_the_future"); }