@Test
public void shouldNotExceedResourceLimitsIfAlreadyAtLimit() throws Exception {

  setResourceLimit("r1", 3);
  initWorkflow(workflowUsingResources(WORKFLOW_ID1, "r1"));
  when(shardedCounter.counterHasSpareCapacity("r1")).thenReturn(false);
  // do not consume resources
  final WorkflowInstance i0 = instance(WORKFLOW_ID1, "i0");
  final WorkflowInstance i1 = instance(WORKFLOW_ID1, "i1");
  final RunState rs0 = RunState.create(i0, State.NEW, time.get(), 17);
  final RunState rs1 = RunState.create(i1, State.QUEUED, time.get(), 4711);
  populateActiveStates(rs0);
  populateActiveStates(rs1);
  // consume resources
  populateActiveStates(runStateWithResources(instance(WORKFLOW_ID1, "i2"), State.PREPARE, "r1"));
  populateActiveStates(runStateWithResources(instance(WORKFLOW_ID1, "i3"), State.PREPARE, "r1"));
  populateActiveStates(runStateWithResources(instance(WORKFLOW_ID1, "i4"), State.PREPARE, "r1"));
  scheduler.tick();
  verify(shardedCounter, times(1)).counterHasSpareCapacity("r1");
  assertThat(eventCaptor.getAllValues().stream()
      .anyMatch(e -> EventUtil.name(e).equals("dequeue")), is(false));
  verify(stats).recordResourceDemanded("r1", 1L);
  verify(stats).recordResourceUsed("r1", 3L);
  scheduler.tick();
  verify(stateManager, times(2)).listActiveInstances();
  verify(shardedCounter, times(2)).counterHasSpareCapacity("r1");
  assertThat(eventCaptor.getAllValues().stream()
      .anyMatch(e -> EventUtil.name(e).equals("dequeue")), is(false));
  verify(stats, times(2)).recordResourceDemanded("r1", 1L);
  verify(stats, times(2)).recordResourceUsed("r1", 3L);
}