@Override
 public synchronized void failed(State from, Throwable failure) {
   assertEquals(from, Iterables.getLast(stateHistory));
   stateHistory.add(State.FAILED);
   assertEquals(State.FAILED, service.state());
   if (from == State.STARTING) {
     try {
       service.startAndWait();
       fail();
     } catch (UncheckedExecutionException e) {
       assertEquals(failure, e.getCause());
     }
   }
   try {
     service.stopAndWait();
     fail();
   } catch (UncheckedExecutionException e) {
     if (from == State.STOPPING) {
       assertEquals(failure, e.getCause());
     } else {
       assertEquals(failure, e.getCause().getCause());
     }
   }
   completionLatch.countDown();
 }
  public void testThrowingServiceStartAndWait() throws Exception {
    StartThrowingService service = new StartThrowingService();
    RecordingListener listener = RecordingListener.record(service);

    try {
      service.startAndWait();
      fail();
    } catch (UncheckedExecutionException e) {
      assertEquals(service.exception, e.getCause());
    }
    assertEquals(ImmutableList.of(State.STARTING, State.FAILED), listener.getStateHistory());
  }
 public void testManualServiceFailureIdempotence() {
   ManualSwitchedService service = new ManualSwitchedService();
   RecordingListener.record(service);
   service.start();
   service.notifyFailed(new Exception("1"));
   service.notifyFailed(new Exception("2"));
   try {
     service.startAndWait();
     fail();
   } catch (UncheckedExecutionException e) {
     assertEquals("1", e.getCause().getMessage());
   }
 }
  public void testFailingServiceStopAndWait_runFailinging() throws Exception {
    RunFailingService service = new RunFailingService();
    RecordingListener listener = RecordingListener.record(service);

    service.startAndWait();
    try {
      service.stopAndWait();
      fail();
    } catch (UncheckedExecutionException e) {
      assertEquals(EXCEPTION, e.getCause().getCause());
    }
    assertEquals(
        ImmutableList.of(State.STARTING, State.RUNNING, State.FAILED), listener.getStateHistory());
  }
 public void testFailureCause_throwsIfNotFailed() {
   StopFailingService service = new StopFailingService();
   try {
     service.failureCause();
     fail();
   } catch (IllegalStateException e) {
     // expected
   }
   service.startAndWait();
   try {
     service.failureCause();
     fail();
   } catch (IllegalStateException e) {
     // expected
   }
   try {
     service.stopAndWait();
     fail();
   } catch (UncheckedExecutionException e) {
     assertEquals(EXCEPTION, service.failureCause());
     assertEquals(EXCEPTION, e.getCause());
   }
 }